Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you explicitly set a new property on `window` in TypeScript?

Tags:

typescript

I setup global namespaces for my objects by explicitly setting a property on window.

window.MyNamespace = window.MyNamespace || {}; 

TypeScript underlines MyNamespace and complains that:

The property 'MyNamespace' does not exist on value of type 'window' any"

I can make the code work by declaring MyNamespace as an ambient variable and dropping the window explicitness but I don't want to do that.

declare var MyNamespace: any;  MyNamespace = MyNamespace || {}; 

How can I keep window in there and make TypeScript happy?

As a side note I find it especially funny that TypeScript complains since it tells me that window is of type any which by definitely can contain anything.

like image 307
joshuapoehls Avatar asked Oct 03 '12 13:10

joshuapoehls


People also ask

How do I extend a TypeScript window?

To extend the window type in TypeScript, create a . d. ts file where you extend the Window interface adding the names and types of the properties you intend to access on the window object.

What is interface window in TypeScript?

Interface Window. A window containing a DOM document; the document property points to the DOM document loaded in that window.

Does not exist on window TypeScript?

The "Property does not exist on type 'Window & typeof globalThis'" error occurs when we access a property that does not exist on the Window interface. To solve the error, extend the Window interface in a . d. ts file and add the property you intend to access on the window object.


1 Answers

I just found the answer to this in another Stack Overflow question's answer.

declare global {     interface Window { MyNamespace: any; } }  window.MyNamespace = window.MyNamespace || {}; 

Basically, you need to extend the existing window interface to tell it about your new property.

like image 112
joshuapoehls Avatar answered Sep 19 '22 14:09

joshuapoehls