TypeScript 6 和 7
如何为 TypeScript 6.0 和 7.0 配置 Bun 的类型定义,这些版本不再自动发现 @types 包。修复升级 TypeScript 后出现的 'Cannot find name Bun' 及其他缺失类型错误。
TypeScript 6.0 改变了发现类型定义的方式。如果你升级了 TypeScript,而编辑器不再识别 @types/bun 中的 Bun、Request 或其他全局变量,以下是修复方法。
变化内容
从 TypeScript 6.0 开始,compilerOptions 中的 types 字段默认变为空数组,而不是包含所有的 @types/* 包。现在你需要显式列出你使用的类型包。
在 tsconfig 中添加 "types": ["bun"]
在你的 tsconfig.json 中,向 compilerOptions 添加 "types": ["bun"]:
tsconfig.json
{
"compilerOptions": {
"types": ["bun"], // [!code ++]
},
}
types 数组告诉 TypeScript 从 @types/bun 加载类型定义。如果你使用其他 @types/* 包,也要将它们包含在内:
tsconfig.json
{
"compilerOptions": {
"types": ["bun", "react"],
},
}
你仍然需要安装 @types/bun。types 选项会告诉 TypeScript 要包含哪些包,但该包本身必须存在于 node_modules 中:
terminal
bun add -d @types/bun
完整的推荐 tsconfig.json
以下是针对使用 TypeScript 6.0 或更高版本的 Bun 项目的完整推荐 tsconfig.json:
tsconfig.json
{
"compilerOptions": {
// 环境设置与最新特性
"lib": ["ESNext"],
"target": "ESNext",
"module": "Preserve",
"moduleDetection": "force",
"jsx": "react-jsx",
"allowJs": true,
"types": ["bun"],
// 打包器模式
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
// 最佳实践
"strict": true,
"skipLibCheck": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"noImplicitOverride": true,
// 一些更严格的标志(默认禁用)
"noUnusedLocals": false,
"noUnusedParameters": false,
"noPropertyAccessFromIndexSignature": false,
},
}
这是否适用于 TypeScript 7?
是的。TypeScript 7 延续了相同的默认行为。如果你直接从 TypeScript 5 升级到 7,同样的修复方法适用——向你的 compilerOptions 添加 "types": ["bun"]。