How to add a new property to a window object in typescript?

This post discusses how to add a property or function to the global scope of the window object in JavaScript or TypeScript.

How to Add an Object to the Window in TypeScript?

The Window object is a built-in global object in JavaScript, offering properties such as location and history, as well as methods like open. These can also be utilized in TypeScript.

Adding a property to a window object in JavaScript and TypeScript can be a bit tricky.

How to Set a New Property to a Window Object in JavaScript?

Yes, you can add properties and methods to the global window object as seen below

window.employee = {}; // global Object container; don't use var
employee.name = 1;
employee.salary = 1;
employee.totalSalary = function () {
  12 * employee.salary;
};
employee.display = function () {
  console.log(employee.name);
};

In JavaScript, without type checking, this will function properly. However, it will result in an error in TypeScript:

The property ‘employee’ does not exist on the value of type ‘window’ any:

Adding properties in TypeScript requires careful handling and can be achieved through multiple approaches.

Custom Interface Extending the Window Object in TypeScript

First, create an interface by extending the Window object and add the desired properties.

interface:EmployeeWindow.ts contains below defination

export interface EmloyeeWindow extends Window {
  name: string;
  salary: Integer;
  totalSalary: Function;
  display: Function;
}

Next, since Window is a global object namespace and doesn’t need to be imported, but a custom interface does, import the interface in the class where it will be used.

CustomWindowExample.ts:

import { EmployeeWindow } from "./EmployeeWindow.ts";

Then, declare a class of type Window object.

declare let window: EmloyeeWindow;

Finally, test by adding properties to the window object.

window.name = 'Franc';
window.salary = 5000;
window.totalSalary = () => {
    return window.salary * 12;
};
window.display = {
    console.log(window.name + ' salary is ' + window.totalSalary)
};

Using any Type in TypeScript

You can create a variable with the type assertion keyword as, indicating to the compiler that it should be considered as a window type:

as is a keyword used to infer the type as a new type

let EmployeeWindow = window as any;
EmployeeWindow.name = 'Franc';
EmployeeWindow.salary = 5000;
EmployeeWindow.totalSalary = () => {
    return window.salary * 12;
};
EmployeeWindow.display = {
    console.log(window.name + ' salary is ' + window.totalSalary)
};

Wrap up

Adding a property to a window object in JavaScript is straightforward, but TypeScript requires additional steps and coding to achieve the same result.