How to Set a New Property on the Window Object in TypeScript

To set a new property on the window object in TypeScript, you can extend the Window interface or use the index notation.

Method 1: Extend the Window interface

You can create a new TypeScript module and extend the Window interface by adding the new property. This way, TypeScript will be aware of the property, and you won’t get any type errors.

Create a new TypeScript file, for example, window.d.ts, and add the following code:

declare global {
  interface Window {
    myNewProperty: string;

Now, in your main TypeScript file or any other file in your project, you can set the new property without getting a type error:

window.myNewProperty = "Homer, Simpson!";

Method 2: Using the index notation

Another approach is to use index notation which doesn’t require extending the Window interface, but it is less type-safe because TypeScript will not check the property’s type.

(window as any)["myNewProperty"] = "Homer, Simpson!";

In this code example, we cast the window object to any and then use index notation to set the new property.

TypeScript will not raise any type errors because it doesn’t check the types of any values.

The first approach (extending the Window interface) is recommended whenever possible because it provides better type safety. Use the second approach only when you need a quick solution and are aware of the potential type safety risks.