我正在使用 Mocha/Chai 进行单元测试并模拟 window
如下:
global.window = { innerHeight: 1000, innerWidth: 1000 };
可以理解,TSLint 提示:
Property 'window' does not exist on type 'Global'
几个问题... Global
是内置的 NodeJS/Typescript 类型吗?我目前正在通过文件顶部的 declare var global
消除警告...但这是处理此问题的最佳方式吗?我注意到我还可以通过以下方式解决警告:
declare global {
namespace NodeJS {
interface Global {
window: any;
}
}
}
最好,我想扩展现有的 Global
类型,使其也接受 window
属性。谢谢。
最佳答案
is
Global
a built-in NodeJS/Typescript type?
是的。参见@types/node/index.d.ts
;在该文件中,他们声明了一个 NodeJS
命名空间,并在其中声明了一个 Global
接口(interface)(就像您所做的那样)。
I'm currently silencing the warning with
declare var global
听起来您没有安装 Node 类型(这些类型包括 declare var global: NodeJS.Global;
行,因此您不必自己进行任何此类声明)。运行:
npm install --save-dev @types/node
或者,如果您使用 yarn
:
yarn add -D @types/node
Preferably, I'd like to extend the existing
Global
type to also accept awindow
property.
你大部分时间都在那里。只需将 window: any;
替换为 window: Window;
。注意:您需要在 tsconfig.json
的 lib
部分包含 dom
以提供 Window
界面。
您可能很快就会发现您还想扩充全局 document
和 navigator
(同样,这两者都在 dom
库中定义,因此需要它):
interface Global {
document: Document;
window: Window;
navigator: Navigator;
}
关于javascript - ( typescript )属性 'window' 在类型 'Global' 上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45948009/