adding to an existing Object prototype in typescript

269 Views Asked by At

I'm using the fantastic Wallaby testing solution to run realtime tests but it -- by default -- intercepts stdout and stderr (for good reasons). In the cases where I do not want this to happen I can override the behavior by tucking a variable into the console command like so:

console._restored = true;

this will be picked up by the Wallaby test runner and temporarily send the event streams back to their normal destinations. This solution works just fine but Typescript isn't happy: ts error message

I am trying to find some way in which to add to the prototype definition of the "Console" interface.

In my first crude attempt, I just looked up the NodeJS definition of Console and added to my test helper file with the _restored property added:

enter image description here

As with most cases of desperation it ended in tears. Apparently the already defined global definition is still used.

Anyway, any help would be appreciated.

2

There are 2 best solutions below

0
ken On BEST ANSWER

My initial attempt was actually close to being right. You can redefine the interface Console as:

// tslint:disable-next-line
interface Console {
    _restored: boolean;
    Console: typeof NodeJS.Console;
    assert(value: any, message?: string, ...optionalParams: any[]): void;
    dir(obj: any, options?: {showHidden?: boolean, depth?: number, colors?: boolean}): void;
    error(message?: any, ...optionalParams: any[]): void;
    info(message?: any, ...optionalParams: any[]): void;
    log(message?: any, ...optionalParams: any[]): void;
    time(label: string): void;
    timeEnd(label: string): void;
    trace(message?: any, ...optionalParams: any[]): void;
    warn(message?: any, ...optionalParams: any[]): void;
}

But then you must also declare console as your newly defined interface:

declare var console: Console;

With this defined in my test helper file, I can now add the following function without error:

export function restoreStdoutAndStderr() {
  console._restored = true;
}
7
toskv On

Extending the Console interface with the property you want to add works in the playground:

interface Console {
    _restored: boolean;
}

console._restored = true;

You can see it working here.

However this does not seem to work when you use modules. In that case you have to define the Console interface in a .d.ts file.

interface Console {
    _restored: boolean;
}

anywhereelse.ts:

import * as something from './something';


console._restored = true;