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

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

此时，你应该可以在 TypeScript 文件中引用全局变量 `Bun`，且编辑器中不会出现错误。

```ts theme={"theme":{"light":"github-light","dark":"dracula"}}
console.log(Bun.version);
```

## 推荐的 `compilerOptions`

Bun 支持诸如顶层 await、JSX 以及带扩展名的 `.ts` 导入，这些是 TypeScript 默认不允许的。下面是一组推荐的 `compilerOptions`，适用于 Bun 项目，这样你可以使用这些特性而不会看到来自 TypeScript 的编译警告。

```jsonc 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 theme={"theme":{"light":"github-light","dark":"dracula"}}
bun init
```
