Visual Studio Code 抱怨 TypeScript 文件中的基本 JavaScript 对象

问题描述 投票:0回答:1

我刚刚在 Visual Studio Code 中打开了一个项目,它现在抱怨无法找到最基本的 JavaScript 对象。

例如,我有这一行:

throw new Error('The [x-confirm] directive can only be used on form elements.');

我从 VS Code 收到

Cannot find name 'Error'
错误。

Error
不是内置的JavaScript类吗?为什么 VS Code(和 TypeScript)突然抱怨这个?

这就是我的 tsconfig.json 文件的样子:

{
    "compilerOptions": {
        "lib": [
            "DOM"
        ],
        "module": "ES6",
        "moduleResolution": "Node",
        "strict": true,
        "target": "ES6",
        "types": [
            "vite/client"
        ]
    },
    "include": [
        "resources/ts/**/*"
    ]
}
typescript visual-studio-code tsconfig
1个回答
0
投票

来自

compilerOptions.lib
的文档:

TypeScript 包含内置 JS API 的一组默认类型定义(如

Math
),以及浏览器环境中找到的内容的类型定义(如
document
)。 TypeScript 还包括与您指定的
target
相匹配的较新 JS 功能的 API;例如,如果
Map
target
或更新版本,则
ES6
的定义可用。

当您指定

compilerOptions.lib
数组时,效果是从编译中删除这些默认环境类型 - 仅包含数组中指定的环境类型。

Error
全局类来自
"ES5"
库中的类型定义(也包含在较新的ES版本库中,例如
"ES2015"
/
"ES6"
"ES2023"
"ESNext"
等) .)。来自源代码

interface Error {
    name: string;
    message: string;
    stack?: string;
}


interface ErrorConstructor {
    new (message?: string): Error;
    (message?: string): Error;
    readonly prototype: Error;
}


declare var Error: ErrorConstructor;

看起来您已经指定了

compilerOptions.lib
字段,但尚未将任何用于核心 ES 功能的库添加到您的编译中,因为数组中的唯一值是
"DOM"
(并且也不是 - 例如 -
"ES6"
)。

要让 TypeScript 识别

Error
,您需要将前面提到的
ES*
库之一添加到您的
compilerOptions.lib
数组中(或完全删除该字段以便使用默认值)。

© www.soinside.com 2019 - 2024. All rights reserved.