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"]。