javascript - ( typescript )属性 'window' 在类型 'Global' 上不存在

标签 javascript node.js typescript

我正在使用 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 a window property.

你大部分时间都在那里。只需将 window: any; 替换为 window: Window;。注意:您需要在 tsconfig.jsonlib 部分包含 dom 以提供 Window 界面。

您可能很快就会发现您还想扩充全局 documentnavigator(同样,这两者都在 dom 库中定义,因此需要它):

interface Global {
    document: Document;
    window: Window;
    navigator: Navigator;
}

关于javascript - ( typescript )属性 'window' 在类型 'Global' 上不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45948009/

相关文章:

javascript - IE 和 Firefox 在滚动()上更新 location.hash 的行为不可预测

javascript - 无法修改作为全局变量初始化的 highcharts

javascript - 构造函数 - 原型(prototype) - __proto__

javascript - 如何从 JavaScript 中的下拉列表中验证 DOB?

jquery - Node.js 上的 Javascript 框架

javascript - 如何从由 no-js 类组成的网页中转储表格数据?

javascript - 如何检查 JSON 对象 ionic2 中的值

node.js - 无法从注册表加载包信息 : The "timeout" argument must be of type number. 收到类型字符串 ('100000' )

javascript - 类型错误 : circular structure to JSON starting at object with constructor 'ClientRequest' property 'socket' -> object with constructor 'Socket'

angular - npm types 或 typings 或 @type 或什么?