Categories
TypeScript Answers

How to create a global variable in TypeScript?

Spread the love

Sometimes, we want to create a global variable in TypeScript.

In this article, we’ll look at how to create a global variable in TypeScript.

How to create a global variable in TypeScript?

To create a global variable in TypeScript, we can put the variable in the Window on Global interfaces in a global type definition file.

For instance, we write

type MyGlobalFunctionType = (name: string) => void;

interface Window {
  myGlobalFunction: MyGlobalFunctionType;
}

in a .d.ts file in our TypeScript project to add the myGlobalFunction property to the Window interface.

Then we can use window.myGlobalFunction any where in our app’s code if it runs in the browser.

Likewise, we can do the same thing to add Node.js global variables by writing

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

to add the myGlobalFunction property into the Global interface if our Node.js TypeScript project.

Then we can use it by writing global.myGlobalFunction in our Node app without compiler errors.

Conclusion

To create a global variable in TypeScript, we can put the variable in the Window on Global interfaces in a global type definition file.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *