Question

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()?)

Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top