Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 383
d512 Avatar asked Jan 29 '16 00:01

d512


People also ask

How do you update a global variable in TypeScript?

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.

Can you explain globals in node JS?

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.

How do I declare a global variable in node JS?

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.

What is globalThis?

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.


1 Answers

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

like image 104
basarat Avatar answered Sep 20 '22 06:09

basarat