silent__thought silent__thought - 1 year ago 162
TypeScript Question

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.MyNamespace = window.MyNamespace || {};

TypeScript underlines
and complains that:

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

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

declare var MyNamespace: any;

MyNamespace = MyNamespace || {};

How can I keep
in there and make TypeScript happy?

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

Answer Source

Just found the answer to this in another StackOverflow question's answer.

interface Window { MyNamespace: any; }

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download