How to use window Object in Browser Environments In Typescript
Assign a property to the window
object for global accessibility in browsers.
Example: In this example, we are using window
Object in Browser Environments to create a global variable in TypeScript.
Javascript
// Using the window object in browser environments (window as any).browserGlobal = "I am a global variable accessible in browsers" ; function useBrowserGlobal() { console.log((window as any).browserGlobal); } useBrowserGlobal(); // Accessible here (in browser environments) |
Output:
I am a global variable accessible in browsers
How to Create a Global Variable in TypeScript ?
To create a global variable in TypeScript, we have multiple approaches. In this article, we are going to learn how to create a global variable in TypeScript.
Below are the approaches used to create a global variable in TypeScript:
Table of Content
- Using var, let or const at the Top Level
- Using window Object in Browser Environments
- Using a Namespace or Module
- Using declare Keyword