Open In App

How to Explicitly Set a New Property on Window in TypeScript ?

In TypeScript, the window object represents the global window in a browser environment. It provides access to various properties and methods related to the browser window. You can set a new custom property on this window object using the below approaches.

By extending the window interface

In this approach, we extend the existing window interface to tell it about the new property. This is done by explicitly defining the window interface and adding a new property to be used within it.

Example: The below code example explains how you can extend the window interface to set a new property on the window in TypeScript.






interface Window { customProperty: any; }
window.customProperty = 
window.customProperty || "GeeksforGeeks";
console.log(window.customProperty);

Output:

GeeksforGeeks

By using the globalThis variable

In this approach, globalThis is utilized which is a global variable that refers to the global scope. It provides a standard way for accessing the global scope which can be used across different environments. Having a consistent way to reference the global object simplifies the development process, promoting code portability and compatibility.

Example: The following example will explain how one can explicitly set a new property on window in TypeScript by using globalThis.




var myCustomProperty: string;
globalThis.myCustomProperty = "GeeksforGeeks"
console.log(window.myCustomProperty);
window.myCustomProperty = 
"GeeksforGeeks is a computer science portal for geeks"
console.log(window.myCustomProperty);

Output:

GeeksforGeeks
GeeksforGeeks is a computer science portal for geeks
Article Tags :