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.
To declare a global variable in TypeScript, create a . d. ts file and use declare global{} to extend the global object with typings for the necessary properties or methods.
Node. js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself as explained below.
To set up a global variable, we need to create it on the global object. The global object is what gives us the scope of the entire project, rather than just the file (module) the variable was created in. In the code block below, we create a global variable called globalString and we give it a value.
The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self , it's guaranteed to work in window and non-window contexts.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With