如何防止“属性'...'不存在于类型'全局'"?使用 jsdom 和打字稿? [英] How to prevent "Property '...' does not exist on type 'Global'" with jsdom and typescript?

查看:40
本文介绍了如何防止“属性'...'不存在于类型'全局'"?使用 jsdom 和打字稿?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将现有项目转换为使用 Typescript,但在我的测试设置中遇到了问题.

I try to convert an existing project to use Typescript and I have problems doing so with my testing setup.

我有一个用于我的测试的设置文件,它设置了 jsdom,以便我的所有 DOM 交互代码在我的测试期间都可以工作.使用 Typescript (ts-node with mocha) 我总是得到这样的错误:

I had a setup file for my tests that sets up jsdom so that all my DOM interacting code works during my tests. Using Typescript (ts-node with mocha) I always get errors like this:

Property 'window' does not exist on type 'Global'.

为了防止这种情况,我尝试像这样修补 NodeJS.Global 接口:

To prevent this I tried patching the NodeJS.Global interface like this:

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

但这并没有改变任何事情.

But this didn't change anything.

如何在 NodeJS 全局变量上启用这些浏览器属性?

How do I enable those browser properties on the NodeJS global variable?

附加:

这是我的摩卡咖啡 setup.ts:

import { jsdom, changeURL } from 'jsdom';

const exposedProperties = ['window', 'navigator', 'document'];

global.document = jsdom('');
global.window = global.document.defaultView;
Object.keys(global.document.defaultView).forEach((property) => {
  if (typeof global[property] === 'undefined') {
    exposedProperties.push(property);
    global[property] = global.document.defaultView[property];
  }
});

global.navigator = {
  userAgent: 'node.js',
};

changeURL(global.window, 'http://example.com/');

推荐答案

避免错误的原始答案

把它放在打字稿文件的顶部

Original Answer To Avoid Error

Put this at the top of your typescript file

const globalAny:any = global;

然后改用 globalAny.

Then use globalAny instead.

globalAny.document = jsdom('');
globalAny.window = global.document.defaultView;

更新答案以维护类型安全

如果你想保持你的类型安全,你可以增加现有的 NodeJS.Global 类型定义.

您需要将您的定义放在全局范围内 declare global {...}

请记住,typescript global 作用域与 NodeJS 接口 Global 或称为 global 属性 不同Global...

Keep in mind that the typescript global scope is not the same as the NodeJS interface Global, or the node global property called global of type Global...

declare global {
  namespace NodeJS {
    interface Global {
       document: Document;
       window: Window;
       navigator: Navigator;
    } 
  }
}

这篇关于如何防止“属性'...'不存在于类型'全局'"?使用 jsdom 和打字稿?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆