7

I used to define global variables using the following code:

interface CustomNodeJSGlobal extends NodeJS.Global {
  myGlobalVariable: unknown
}

export { CustomNodeJSGlobal }

In Node 14, but when I installed @types/node (which is currently in the version 16) it throws me an error Namespace 'NodeJS' has no exported member 'Global'. How can I declare global variables in Node 16 and above?

Anthony Luzquiños
  • 739
  • 11
  • 23
  • Did you configured node types in your `tsconfig.json` ? – Giovanni Esposito Jul 05 '21 at 07:01
  • You mean `types` field in `compilerOptions`? – Anthony Luzquiños Jul 05 '21 at 07:03
  • Yes, when you declare `types` like `"types": [ "node", ... ]` – Giovanni Esposito Jul 05 '21 at 07:09
  • No, I haven't used that field, what should I put there? – Anthony Luzquiños Jul 05 '21 at 14:36
  • The following answer may help you (but will not directly answer your question): https://stackoverflow.com/questions/68262350/how-can-i-resolve-the-tsc-error-namespace-nodejs-has-no-exported-member-glob#answer-68262351 – derekbaker783 Jul 05 '21 at 21:43
  • Does this answer your question? [Extending TypeScript Global object in node.js](https://stackoverflow.com/questions/35074713/extending-typescript-global-object-in-node-js) – Parzh from Ukraine Oct 06 '21 at 09:55
  • This would be the direct answer to the question: https://stackoverflow.com/a/68328575/4554883 – Parzh from Ukraine Oct 06 '21 at 09:56
  • Thanks guys, it, I already checked your suggestions, and I found 2 more that are related to my question: https://stackoverflow.com/a/56984941/12379333 and https://stackoverflow.com/a/69230938/12379333, but neither of them works for me without adding `// @ts-ignore`, bcs the compiler complains with the following error: 'Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature'. – Anthony Luzquiños Oct 19 '21 at 15:31

1 Answers1

5

With Node.js >= 16, I think NodeJS.Global type is no longer available, but you can declare it like:

type NodeJSGlobal = typeof global;
jarmod
  • 71,565
  • 16
  • 115
  • 122
Davide Icardi
  • 11,919
  • 8
  • 56
  • 77