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.
I wanted to use this in an Angular (6) library today and it took me a while to get this to work as expected.
In order for my library to use declarations I had to use the
d.ts
extention for the file that declares the new properties of the global object.So in the end, the file ended up with something like:
/path-to-angular-workspace/angular-workspace/projects/angular-library/src/globals.d.ts
Once created, don't forget to expose it in your
public_api.ts
.That did it for me. Hope this helps.
Just found the answer to this in another StackOverflow question's answer.
Basically you need to extend the existing
window
interface to tell it about your new property.Using TSX? None of the other answers were working for me.
Here's what I did:
I don't need to do this very often, the only case I have had was when using Redux Devtools with middleware.
I simply did:
Or you could do:
let myWindow = window as any;
and then
myWindow.myProp = 'my value';
Or...
you can just type:
and you wont get a compile error and it works the same as typing
window.MyNamespace
Here's how to do it, if you're using TypeScript Definition Manager!
Create
typings/custom/window.d.ts
:Install your custom typing:
Done, use it! Typescript won't complain anymore: