> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript 6 和 7

> 如何为 TypeScript 6.0 和 7.0 配置 Bun 的类型定义，这些版本不再自动发现 @types 包。修复升级 TypeScript 后出现的 'Cannot find name Bun' 及其他缺失类型错误。

TypeScript 6.0 改变了类型定义的发现方式。如果你升级了 TypeScript 后，编辑器不再识别 `Bun`、`Request` 或来自 `@types/bun` 的其他全局变量，以下是修复方法。

## 变化内容

从 TypeScript 6.0 开始，`compilerOptions` 中的 `types` 字段默认变为空数组，而不是包含所有的 `@types/*` 包。现在你需要显式列出你使用的类型包。

## 在 tsconfig 中添加 `"types": ["bun"]`

在你的 `tsconfig.json` 中，向 `compilerOptions` 添加 `"types": ["bun"]`：

```jsonc tsconfig.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  "compilerOptions": {
    "types": ["bun"], // [!code ++]
  },
}
```

这告诉 TypeScript 从 `@types/bun` 加载类型定义。如果你使用其他 `@types/*` 包，也请一并包含：

```jsonc tsconfig.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  "compilerOptions": {
    "types": ["bun", "react"],
  },
}
```

你仍然需要安装 `@types/bun` —— `types` 选项告诉 TypeScript 要包含哪些包，但包本身必须存在于 `node_modules` 中：

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun add -d @types/bun
```

## 完整的推荐 tsconfig.json

以下是针对使用 TypeScript 6.0 或更高版本的 Bun 项目的完整推荐 `tsconfig.json`：

```jsonc tsconfig.json icon="file-json" theme={"theme":{"light":"github-light","dark":"dracula"}}
{
  "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"]`。
