In many cases when you’re working with TypeScript, there are type definitions available for almost every package out there.
However, in some circumstances, you might find yourself working with a third party that adds a property to the window object. Think a script tag like how Google Analytics works by adding in the ga
property to the window.
It doesn’t matter if you are using Angular, React, Vue, Svelte, Aurelia, or any other framework or library, this approach works for all TypeScript projects.
Presumably, all of your source code is in a folder called src
(it’s the most common place). You can name this file anything, but create a new file called index.d.ts
and add in the following.
export {}; declare global { interface Window { globalProp: any; } }
This will add type support for window.globalProp
and stop TypeScript complaining about this property not existing. In the above example, we use “any"
for situations where you just want it to work so, you can compile your code, but it’s better to properly type your defined properties where possible.
It’s rare that I need to add new properties to the window object, so this post is more a reference for myself and anyone else who can’t remember the right way to do this.