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

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.


To keep it dynamic, just use:

(<any>window).MyNamespace

Note that this may not work with TSX because the compiler might think that the <any> is a TSX element. Check out this answer for type assertion that is compatible with TSX.

Tags:

Typescript