> ## 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

> 在 Bun 中使用 TypeScript，包括类型定义和编译器选项

要安装 Bun 内置 API 的 TypeScript 类型定义，请安装 `@types/bun`。

```zsh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun add -d @types/bun # 开发依赖
```

此时，你应该能够在 TypeScript 文件中引用全局的 `Bun`，而编辑器不会报错。

## 推荐的 `compilerOptions`

Bun 支持顶层 await、JSX 以及带扩展名的 `.ts` 导入，而这些是 TypeScript 默认不允许的。下面是一个针对 Bun 项目的推荐 `compilerOptions` 配置，方便你使用这些特性且不会看到 TypeScript 的编译警告。

```json 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
  }
}
```

如果你在一个新目录运行 `bun init`，这个 `tsconfig.json` 会自动为你生成。（更严格的标志默认是禁用的。）

```sh terminal icon="terminal" theme={"theme":{"light":"github-light","dark":"dracula"}}
bun init
```

## TypeScript 6 和 7

如果你使用的是 TypeScript 6.0 或更高版本，还需要在 `compilerOptions` 中添加 `"types": ["bun"]`。详情请参见 [TypeScript 6 和 7](/typescript-6)。
