Use global variable in Typescript with Nodejs

Asked

Viewed 809 times

1

I am looking for a way to use global variable in typescript with Nodejs. For example in js I can do:

//init.js
  global.foo = "foo";
//teste.js
  var foo = global.foo;

Is there any way to do this in typescript? PS: I know it’s not good practice, but I’d like to learn.

1 answer

1

It is possible yes, but as you said yourself, it is not very cool to use globals, one way to do it is to create a module and an interface within this module, like this example:

File name: global.d.ts (Example name, usually used with this suffix for directives)

declare module NodeJS {
export interface Global {
    __base_path: any,
    __helpers_path: any,
    __emails_path: any,
    __config: any,

}    

And then declare in your tsconfig.js this module, as this example:

{
    "compilerOptions": {
        "module": "commonjs",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true,
        "target": "es6",
        "baseUrl": "./",
    },
    "files": [
        "global.d.ts"
    ]
}

You can observe the files there with the global.d.ts, leaving explicit this module being imported.

With these two procedures you guarantee that the global ones will work with the TS, but even so the Typescript compiler can complain of not finding the global variables. To solve this (gambiarra), you can declare a variable called globaany, with type any and assign globals to it, and then use globalany with its global ones. Let me show you an example of code to make it clearer.

No TS build error

const globalAny: any = global
globalAny.__basepath //return basepath

With TS build error

const basepath = global.__basepath

Browser other questions tagged

You are not signed in. Login or sign up in order to post.