How to prevent “Property '…' does not exist on type 'Global'” with jsdom and typescript?

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-29 22:16:56

Original Answer To Avoid Error

Put this at the top of your typescript file

const globalAny:any = global;

Then use globalAny instead.

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

Updated Answer To Maintain Type Safety

If you want to keep your type safety, you can augment the existing NodeJS.Global type definition.

You need to put your definition inside the global scope declare 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;
  }
}

In addition to other answers, you can also simply cast global directly at the assignment site:

(global as any).myvar = myvar;

I fixed this problem by doing this...

export interface Global {
  document: Document;
  window: Window;
}

declare var global: Global;
declare namespace NodeJS {
  export interface Global { window: any;
  }
}

Avoid typecasting any, it removes the purpose of typings. Instead install the type definitions needed (e.g. yarn add --dev @types/jsdom @types/node) and import to use:

import { DOMWindow, JSDOM } from 'jsdom'

interface Global extends NodeJS.Global {
  window: DOMWindow,
  document: Document,
  navigator: {
    userAgent: string
  }
}

const globalNode: Global = {
  window: window,
  document: window.document,
  navigator: {
    userAgent: 'node.js',
  },
  ...global
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!