Typescript Conflicting Variable Names

Typescript Conflicting Variable Names

Problem

I’m trying to compile some Node.js Typescript code, but I’m having issues with two variables named console. Essentially, Node.js has a console.trace() method, while normal browser side Javascript does not. I have node.d.ts referenced in my Typescript file and everything else works just fine. node.d.ts declares console as a variable, but so does lib.d.ts, which seems to be overriding the Node.js version. Adding –nolib to the compiler just throws hundreds of errors about undefined symbols. Is there a way to get around this without editing lib.d.ts? (Or casting console: (<any>console).trace()?)

Problem courtesy of: GJK

Solution

You can edit the node.d.ts definition to make it extend the existing lib.d.ts definition of the Console interface.

In your node.d.ts replace declare var console with:

interface Console {
    log(...data: any[]): void;
    info(...data: any[]): void;
    error(...data: any[]): void;
    warn(...data: any[]): void;
    dir(obj: any): void;
    timeEnd(label: string): void;
    trace(label: string): void;
    assert(expression: any, ...message: string[]): void;
}

Now your TypeScript will compile without the cast to any

Solution courtesy of: dmck

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *