Use global variable in Typescript with NodeJS

1

I'm 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 I can do this in typescript? PS: I know it's not good practice, but I'd like to learn.

    
asked by anonymous 07.09.2018 / 18:43

1 answer

1

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

File name: global.d.ts (Sample 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, like this example:

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

You can see the files there with global.d.ts, leaving this module explicitly imported.

With these two procedures you ensure that the global ones will work with TS, but the Typescript compiler can still complain about not finding the global variables. To resolve this ( gambiarra ), you can declare a variable called globaany, with type any and assign globals to it, and then use globalany with its globals. I'll show you an example code to make it clearer.

No TS build error

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

With TS compilation error

const basepath = global.__basepath
    
26.09.2018 / 04:24