178

I would like to store my NodeJS config in the global scope.

I tried to follow this => Extending TypeScript Global object in node.js and other solution on stackoverflow,

I made a file called global.d.ts where I have the following code

declare global {
    namespace NodeJS {
      interface Global {
          config: MyConfigType
      }
    }
  }

Augmentations for the global scope can only be directly nested in external modules or ambient module declarations.ts(2669)

but doing this works fine =>

declare module NodeJS  {
    interface Global {
        config: MyConfigType
    }
}

the problem is, I need to import the file MyConfigType to type the config, but the second option do not allow that.

3
  • 4
    Understand that an "external module" is a file containing an import or export statement, that an "ambient module declaration" reads declare module "m" {} (note the quotes), and reread the error message. Jul 21, 2019 at 10:59
  • 8
    You might need export {}
    – Polv
    Oct 10, 2019 at 19:21
  • 5
    In an ambient decl. file that's not been turned into a module you are already operating in the global scope (outside of declare module {} braces) so you can just omit declare global
    – Dominic
    Mar 7, 2020 at 13:54

2 Answers 2

355

You can indicate that the file is a module like so:

export {};

declare global {
    namespace NodeJS {
        interface Global {
            config: MyConfigType
        }
    }
}
4
  • 32
    wow, works! What trickery is this "export {};". Can you provide some information that I can read up on as to why that works? Jul 11, 2020 at 2:52
  • 9
    I think the trick is just that an "external module" is a file containing an import or export statement, so this makes it an "external module". It does seem a little strange that this is needed though...
    – Tyler Rick
    Sep 4, 2020 at 17:56
  • 3
    @user1949561 here's a good explanation of why stackoverflow.com/a/42257742/1048847
    – okcoker
    Nov 28, 2021 at 21:52
  • 1
    I think that declaring MyConfigType in another file and then using import should fix the issue too. (if this option is applicable to your case)
    – mikey
    Feb 14, 2022 at 4:24
37

Or if you're trying to add a global type within the browser context:

export {};

declare global {
  interface Window {
    ENV: any;
  }
}
3
  • Hmmm. Just tried this but every time I close the .d.ts file the variable that's on the window is underlined in red as an error. The error goes away when I open the window.
    – LJD
    Feb 22, 2022 at 1:38
  • @LJD try adding the file to tsconfig.json: "include": ["globals.d.ts"]
    – Isaac
    Jan 30 at 22:09
  • Thanks, that probably would have done it.
    – LJD
    Jan 31 at 5:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.