[英](Typescript) Property 'window' does not exist on type 'Global'
I am using Mocha/Chai to unit test and am mocking window
as follows: 我正在使用Mocha / Chai进行单元测试,并模拟
window
如下:
global.window = { innerHeight: 1000, innerWidth: 1000 };
Understandably, TSLint is complaining that: 可以理解,TSLint抱怨:
Property 'window' does not exist on type 'Global'
属性“窗口”在类型“全局”上不存在
A few questions... is Global
a built in NodeJS/Typescript type? 几个问题...
Global
是内置的NodeJS / Typescript类型吗? I'm currently silencing the warning with declare var global
at the top of the file... but is this the best way to handle this? 我目前正在使用文件顶部的
declare var global
消除警告...但这是处理此问题的最佳方法吗? I noticed I can also resolve the warning with: 我注意到我也可以通过以下方式解决警告:
declare global {
namespace NodeJS {
interface Global {
window: any;
}
}
}
Preferably, I'd like to extend the existing Global
type to also accept a window
property. 最好,我想扩展现有的
Global
类型以也接受window
属性。 Thanks. 谢谢。
is
Global
a built-in NodeJS/Typescript type?Global
是内置的NodeJS / Typescript类型吗?
Yes. 是。 See
@types/node/index.d.ts
; 参见
@types/node/index.d.ts
; in that file, they declare a NodeJS
namespace, and within that, a Global
interface (just as you've done). 在该文件中,它们声明一个
NodeJS
命名空间,并在其中声明一个Global
接口(正如您所做的那样)。
I'm currently silencing the warning with
declare var global
我目前正在使用
declare var global
消除警告
Sounds like you don't have the Node typings installed (those typings include the line declare var global: NodeJS.Global;
so you shouldn't have to make any such declarations yourself). 听起来好像您没有安装Node类型(这些类型包括
declare var global: NodeJS.Global;
因此您不必自己进行任何此类声明)。 Run: 跑:
npm install --save-dev @types/node
or, if you use yarn
: 或者,如果您使用
yarn
:
yarn add -D @types/node
Preferably, I'd like to extend the existing
Global
type to also accept awindow
property.最好,我想扩展现有的
Global
类型以也接受window
属性。
You're mostly there. 您大部分都在那儿。 Just replace
window: any;
只需替换
window: any;
with window: Window;
带
window: Window;
. 。 Note: you will need your
tsconfig.json
's lib
section to include dom
to provide the Window
interface. 注意:您将需要
tsconfig.json
的lib
部分包含dom
来提供Window
界面。
You may soon find that you also want to augment Global document
and navigator
(again, both of these are defined in the dom
lib, and hence require it): 您可能很快会发现,您还想扩充Global
document
和navigator
(同样,这两个都是在dom
lib中定义的,因此需要它):
interface Global {
document: Document;
window: Window;
navigator: Navigator;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.