TypeScript: Property 'X' does not exist on 'Window & typeof globalThis': suggested solution using 'declare global' gives me error TypeScript: 属性 'X' 在 'Window & typeof globalThis' 上不存在:使用 'declare global' 的建议解决方案导致错误

18 浏览
0 Comments

TypeScript: Property 'X' does not exist on 'Window & typeof globalThis': suggested solution using 'declare global' gives me error TypeScript: 属性 'X' 在 'Window & typeof globalThis' 上不存在:使用 'declare global' 的建议解决方案导致错误

编辑:这是一个ESlint问题。我在这篇帖子的末尾包含了我的ESLint设置。

我对TypeScript还比较新手-我正在为一个工作项目重构别人的React代码,并将其转换为TypeScript,当我遇到这行代码时:

const memoryOptionsResponse = window.webchatMethods.getMemory(chatId);

TypeScript抱怨'window.webchat',说:

“Window & typeof globalThis上不存在属性'X'”。

经过一些搜索,答案似乎是将以下内容放在模块的根级别:

declare global {
    interface Window {
        webchatMethods: any;
    }
}

然而,现在TypeScript报错如下。这个Stack Overflow页面提供了类似的建议,但是它也有`declare global`,ESLint不接受。

在尝试修复了半个小时后,我决定向您寻求建议-如果有人知道一个好的解决方案,我将不胜感激!

.eslintconfig文件内容如下:

{

"parser": "babel-eslint",

"parserOptions": {

"ecmaVersion": 2020,

"sourceType": "module",

"ecmaFeatures": {

"jsx": true,

"modules": true

}

},

"extends": [

"eslint:recommended",

"prettier",

"plugin:react/recommended"

],

"plugins": [

"prettier",

"react",

"react-hooks"

],

"env": {

"es6": true,

"node": true,

"mocha": true,

"browser": true

},

"rules": {

"react-hooks/rules-of-hooks": "error",

"react-hooks/exhaustive-deps": "warn",

"react/prop-types": 1,

"react/jsx-uses-react": "error",

"react/jsx-uses-vars": "error",

"react/no-unescaped-entities": "warn",

"react/no-find-dom-node": 0,

"comma-dangle": ["error", "never"],

"global-require": 0

}

}

.eslintignore文件内容如下:

test
node_modules

0
0 Comments

问题的出现原因是缺少告诉babel如何处理TypeScript的部分。可以通过查看typescript-eslint的文档来解决这个问题。

0