How do you explicitly set a new property on `windo

2019-01-01 01:22发布

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.

标签: typescript
15条回答
流年柔荑漫光年
2楼-- · 2019-01-01 02:02

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.

查看更多
旧时光的记忆
3楼-- · 2019-01-01 02:04

Just found the answer to this in another StackOverflow 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.

查看更多
回忆,回不去的记忆
4楼-- · 2019-01-01 02:05

Using TSX? None of the other answers were working for me.

Here's what I did:

(window as any).MyNamespace
查看更多
明月照影归
5楼-- · 2019-01-01 02:06

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:

const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

Or you could do:

let myWindow = window as any;

and then myWindow.myProp = 'my value';

查看更多
余生无你
6楼-- · 2019-01-01 02:09

Or...

you can just type:

window['MyNamespace']

and you wont get a compile error and it works the same as typing window.MyNamespace

查看更多
残风、尘缘若梦
7楼-- · 2019-01-01 02:13

Here's how to do it, if you're using TypeScript Definition Manager!

npm install typings --global

Create typings/custom/window.d.ts:

interface Window {
  MyNamespace: any;
}

declare var window: Window;

Install your custom typing:

typings install file:typings/custom/window.d.ts --save --global

Done, use it‌! Typescript won't complain anymore:

window.MyNamespace = window.MyNamespace || {};
查看更多
登录 后发表回答