Create A Global Variable In TypeScript


Answer :

Inside a .d.ts definition file



type MyGlobalFunctionType = (name: string) => void


If you work in the browser,
you add members to the browser's window context:



interface Window {
myGlobalFunction: MyGlobalFunctionType
}


Same idea for NodeJS:



declare module NodeJS {
interface Global {
myGlobalFunction: MyGlobalFunctionType
}
}


Now you declare the root variable (that will actually live on window or global)



declare const myGlobalFunction: MyGlobalFunctionType;


Then in a regular .ts file, but imported as side-effect, you actually implement it:



global/* or window */.myGlobalFunction = function (name: string) {
console.log("Hey !", name);
};


And finally use it elsewhere in the codebase, with either:



global/* or window */.myGlobalFunction("Kevin");

myGlobalFunction("Kevin");


globalThis is the future.



First, TypeScript files have two kinds of scopes



global scope



If your file hasn't any import or export line, this file would be executed in global scope that all declaration in it are visible outside this file.



So we would create global variables like this:



// xx.d.ts
declare var age: number

// or
// xx.ts
// with or without declare keyword
var age: number

// other.ts
globalThis.age = 18 // no error



All magic come from var. Replace var with let or const won't work.




module scope



If your file has any import or export line, this file would be executed within its own scope that we need to extend global by declaration-merging.



// xx[.d].ts
declare global {
var age: number;
}

// other.ts
globalThis.age = 18 // no error



You can see more about module in official docs




This is how I have fixed it:



Steps:




  1. Declared a global namespace, for e.g. custom.d.ts as below :



declare global {
namespace NodeJS {
interface Global {
Config: {}
}
}
}
export default global;



  1. Map the above created a file into "tsconfig.json" as below:



"typeRoots": ["src/types/custom.d.ts" ]



  1. Get the above created global variable in any of the files as below:



console.log(global.config)


Note:




  1. typescript version: "3.0.1".


  2. In my case, the requirement was to set the global variable before boots up the application and the variable should access throughout the dependent objects so that we can get the required config properties.




Hope this helps!



Thank you



Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable