Search code examples
typescript

How do you explicitly set a new property on `window` in 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.


Solution

  • 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.