Crocsx
Crocsx

Reputation: 7589

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

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.

Upvotes: 246

Views: 112127

Answers (3)

Cobertos
Cobertos

Reputation: 2253

If your .d.ts is executing as a "script" (it has no import/export statements), you won't need to declare global at all, and can simply remove it. A "script" is already executing in the global context.

(aside: this is why adding export {} works, it turns it from a "script" into a "module" and your declarations in the .d.ts are no longer global by default)

With an example modifying console:

Before:

declare global {
  interface Console {
    log2: (...args: any[])=>void;
  }
}

After:

// This will be global!
interface Console {
  log2: (...args: any[])=>void;
}

Thanks to @okcoker and https://stackoverflow.com/a/42257742/2759427 for the explanation of .d.ts contexts

Upvotes: 19

Ben Winding
Ben Winding

Reputation: 11787

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

export {};

declare global {
  interface Window {
    ENV: any;
  }
}

Upvotes: 51

sshh
sshh

Reputation: 7092

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

export {};

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

Upvotes: 486

Related Questions