TypeScript 中的 Duplicate identifier 错误
要解决“Duplicate identifier 错误”:
- 确保我们没有任何冲突的标识符名称。
- 在 tsconfig.json 文件中将 skipLibCheck 选项设置为 true。
- 更新typescript 版本,例如
npm i -D @types/node@latest
。
有时,当我们使用与全局定义的对象、全局接口或不同文件中具有相同名称的成员(如果不使用 ES 模块)冲突的名称时会导致错误。
// ⛔️ Duplicate identifier 'Employee'.ts(2300)
class Employee {}
// ⛔️ Duplicate identifier 'Node'.ts(2300)
class Node {} // ?️ name of global interface
// ⛔️ Duplicate identifier 'Array'.ts(2300)
class Array {} // ?️ name of global interface
Employee
类导致错误,因为该文件不是 ES 模块。 模块是包含至少 1 个导入或导出语句的文件。
如果我们的文件不包含至少 1 个 import
或 export
语句,则将其视为全局旧脚本,这是错误的常见原因。
如果我们没有要导出的内容,只需 export {}
。
// ✅ It's an ES module now
class Employee {}
export {};
我们使用文件中的 export {}
行将其标记为 ES 模块。
确保我们没有在代码中使用任何全局接口或对象的名称,例如 Node、Array、String。
“Duplicate identifier Error”错误的另一个常见原因是 – 我们的项目正在从包的多个版本中提取类型。
在 tsconfig.json 中将 skipLibCheck
选项设置为 true。
{
"compilerOptions": {
"skipLibCheck": true,
// ... rest
},
"include": ["src/**/*"],
"exclude": ["node_modules"]
}
skipLibCheck
选项指示编译器跳过声明文件的类型检查。
这是必需的,因为有时两个库定义了相同类型的两个副本。
如果没有,请确保将 node_modules 添加到我们的 exclude
数组(如上面的代码片段中)。
如果我们的错误消息显示类型包的名称,例如 /node_modules/typescript/lib….
我们必须更新 @types/node
的版本。 例如,这是更新 @types/node
版本的方式。
$ npm i -D @types/node@latest
确保安装最新版本的 @types
包,因为我们可能有旧版本(或多个版本)。
如果我们的依赖项中有 types/node
包,请务必运行 npm i -D @types/node@latest
因为它经常会导致错误。
如果错误未解决,请尝试删除 node_modules 和 package-lock.json 文件,重新运行 npm install
并重新启动 IDE。
$ rm -rf node_modules package-lock.json
$ npm install
如果错误仍然存在,请确保重新启动 IDE 和开发服务器。 VSCode 经常出现故障,有时重启可以解决问题。