> ## 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，包括类型定义和编译器选项

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

```sh theme={null}
bun add -d @types/bun # 开发依赖
```

现在你可以在 TypeScript 文件中引用 `Bun` 全局变量，而不会在编辑器中看到错误。

```ts theme={null}
console.log(Bun.version);
```

## 建议的 `compilerOptions`

Bun 支持顶层 await、JSX 以及带 `.ts` 扩展名的导入，而 TypeScript 默认不允许这些。以下是 Bun 项目推荐的 `compilerOptions`，让你可以在不收到 TypeScript 编译器警告的情况下使用这些功能。

```jsonc 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 theme={null}
bun init
```
