Horje
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.

Javascript

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.

Javascript

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



Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
How to Create a New Line in JavaScript ? How to Create a New Line in JavaScript ?
How to Log the Current Date in JavaScript ? How to Log the Current Date in JavaScript ?
How to Iterate Through Numbers and Return a String Message if the Sum is Negative? How to Iterate Through Numbers and Return a String Message if the Sum is Negative?
How to Declare Object Value Type Without Declaring Key Type in TypeScript ? How to Declare Object Value Type Without Declaring Key Type in TypeScript ?
Create a Facebook Post Box Clone in HTML CSS & JavaScript Create a Facebook Post Box Clone in HTML CSS & JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13