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

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

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

```zsh terminal icon="terminal" theme={null}
bun add -d @types/bun # 开发依赖
```

之后，你就可以在 TypeScript 文件中引用 `Bun` 全局对象，而不会在编辑器中看到错误。

## 推荐的 `compilerOptions`

Bun 支持顶层 await、JSX 以及带 `.ts` 扩展名的导入，这些默认情况下 TypeScript 是不允许的。在 Bun 项目中使用以下 `compilerOptions`，以便 TypeScript 不会对这些功能发出警告。

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

在新目录中运行 `bun init` 会自动为你生成这个 `tsconfig.json`。

```sh terminal icon="terminal" theme={null}
bun init
```

## TypeScript 6 和 7

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