typescriptwallaby.js

adding to an existing Object prototype in typescript


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.


Solution

  • 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;
    }