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.
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.
Interface Window. A window containing a DOM document; the document property points to the DOM document loaded in that window.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With