How to add new property to window object in typescript


Window is inbuilt JavaScript global object, It provides properties like location and history and also methods like open. It is tricky one to add an property in window object in javascript and typescript

This post talks about how do you add property or function in window global namescope in javascript or typescript

How do you set new property to window object in javascript?

Yes, We can add properties,methods in window global 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); 
}

As javascript, there is not type checking, This will works, However, This will not works in typescript and gives following error.

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

So adding property in typescript is an trickey and can be done with multiple approaches

Custom Interface Extends window object in typescript

Create a interface by extending Window object. Add the properties that you want to add

Let’s Create EmployeeWindow.ts

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

}

Window is an global object namespace which is not required to import, But custom interface needs to import in a class into you want to use

CustomWindowExample.ts:

import {EmloyeeWindow} from './EmployeeWindow.ts';

Third step is to declare a class of type Window object

declare let window: EmloyeeWindow;

You can test the same with adding properties into window object.

window.name = 'Franc';
window.salary = 5000;


window.totalSalary = () => {
    return window.salary*12;
};


window.display = {
   console.log(window.name +' salary is '+ window.totalSalary)
};

Any type in typescript

Please create a variable with type assertion keyword as, that means compiler understood and consider this as window type. as is a keyword used to infer the type as 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 property to window object in javascript indeed simple and easy, However Typescript needs litle extra coding and steps required to set property in window object.

Similar Posts