Search code examples
node.jstypescriptglobal

Extending TypeScript Global object in node.js


I have a node.js app that attaches some config information to the global object:

global.myConfig = {
    a: 1,
    b: 2
}

The TypeScript compiler doesn't like this because the Global type has no object named myConfig:

TS2339: Property 'myConfig' does not exist on type 'Global'.

I don't want to do this:

global['myConfig'] = { ... }

How do I either extend the Global type to contain myConfig or just tell TypeScript to shut up and trust me? I'd prefer the first one.

I don't want to change the declarations inside node.d.ts. I saw this SO post and tried this:

declare module NodeJS  {
    interface Global {
        myConfig: any
    }
}

as a way to extend the existing Global interface, but it doesn't seem to have any effect.


Solution

  • I saw this SO post and tried this:

    You probably have something like vendor.d.ts:

    // some import 
    // AND/OR some export
    
    declare module NodeJS  {
        interface Global {
            spotConfig: any
        }
    }
    

    Your file needs to be clean of any root level import or exports. That would turn the file into a module and disconnect it from the global type declaration namespace.

    More : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html