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.
Javascript
var myCustomProperty: string; globalThis.myCustomProperty = "w3wiki" ; console.log(window.myCustomProperty); window.myCustomProperty = "w3wiki is a computer science portal for geeks" ; console.log(window.myCustomProperty); |
Output:
w3wiki
w3wiki is a computer science portal for geeks
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.
Table of Content
- By extending the window interface
- By using the globalThis variable