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

# TypeScript 6 和 7

> 如何为 TypeScript 6.0 和 7.0 配置 Bun 的类型定义，这些版本不再自动发现 @types 包。修复升级 TypeScript 后出现的 '找不到名称 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={null}
{
  "compilerOptions": {
    "types": ["bun"], // [!code ++]
  },
}
```

`types` 数组告诉 TypeScript 从 `@types/bun` 加载类型定义。如果你使用其他 `@types/*` 包，也一起包含它们：

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

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

```sh terminal icon="terminal" theme={null}
bun add -d @types/bun
```

## 完整的推荐 tsconfig.json

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

```jsonc tsconfig.json icon="file-json" theme={null}
{
  "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"]`。
