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

# TypeScript

> Using TypeScript with Bun, including type definitions and compiler options

## Overview

Bun is designed with TypeScript in mind. It natively executes TypeScript and TSX files without requiring a separate transpilation step. This makes Bun an ideal runtime for TypeScript projects.

```bash terminal icon="terminal" theme={null}
bun run index.ts
bun run component.tsx
```

<Note>Bun's transpiler only strips TypeScript syntax—it doesn't perform type checking. Use `tsc` (the official TypeScript compiler) for type checking in development and CI.</Note>

***

## Install type definitions

To install TypeScript type definitions for Bun's built-in APIs, install `@types/bun`:

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

At this point, you should be able to reference the global `Bun` object in your TypeScript files without seeing errors in your editor.

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

<Accordion title="What is @types/bun?">
  The `@types/bun` package is a shim package that re-exports types from `bun-types`, which lives in the Bun repository under `packages/bun-types`.

  The types include:

  * The global `Bun` namespace with all runtime APIs
  * Type definitions for `bun:*` built-in modules like `bun:test`, `bun:sqlite`, `bun:ffi`
  * Augmented types for Node.js compatibility APIs
  * Web API types that extend standard TypeScript lib types
</Accordion>

***

## Recommended `tsconfig.json`

Bun supports features like top-level `await`, JSX, and extensioned imports (`.ts` imports) that TypeScript doesn't allow by default. Here's a recommended `tsconfig.json` for Bun projects that enables these features without compilation warnings:

```json tsconfig.json icon="file-json" theme={null}
{
  "compilerOptions": {
    // Environment & latest features
    "lib": ["ESNext"],
    "target": "ESNext",
    "module": "Preserve",
    "moduleDetection": "force",
    "jsx": "react-jsx",
    "allowJs": true,

    // Bundler mode
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "noEmit": true,

    // Best practices
    "strict": true,
    "skipLibCheck": true,
    "noFallthroughCasesInSwitch": true,
    "noUncheckedIndexedAccess": true,
    "noImplicitOverride": true,

    // Some stricter flags (disabled by default)
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "noPropertyAccessFromIndexSignature": false
  }
}
```

If you run `bun init` in a fresh directory, this `tsconfig.json` will be auto-generated for you.

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

### Key compiler options explained

<Accordion title="module: Preserve">
  Sets the module system to `Preserve`, which keeps import/export statements as-is without transforming them. This is ideal for Bun since it natively supports ESM.
</Accordion>

<Accordion title="moduleResolution: bundler">
  Uses the `bundler` resolution algorithm, which matches the behavior of modern bundlers and runtimes like Bun. This enables features like:

  * Importing TypeScript files with `.ts` extensions
  * Proper resolution of `exports` field in `package.json`
  * Support for extensionless imports
</Accordion>

<Accordion title="allowImportingTsExtensions: true">
  Allows importing TypeScript files with `.ts` and `.tsx` extensions:

  ```ts theme={null}
  import { foo } from "./foo.ts"; // ✅ Allowed
  ```

  Without this flag, TypeScript would require you to omit the extension.
</Accordion>

<Accordion title="verbatimModuleSyntax: true">
  Ensures that import/export statements are preserved exactly as written. This helps catch errors where you might accidentally use `import type` syntax that would be stripped.
</Accordion>

<Accordion title="noEmit: true">
  Prevents TypeScript from generating output files. Since Bun handles transpilation at runtime, you don't need TypeScript to emit JavaScript files.
</Accordion>

***

## Native TypeScript features

Bun supports several TypeScript features natively:

### Top-level await

Use `await` at the top level of your modules:

```ts index.ts icon="https://mintlify.s3.us-west-1.amazonaws.com/zhcndoc-bun/icons/typescript.svg" theme={null}
const response = await fetch("https://api.example.com/data");
const data = await response.json();

console.log(data);
```

### JSX and TSX

Bun can execute `.jsx` and `.tsx` files directly:

```tsx Component.tsx icon="https://mintlify.s3.us-west-1.amazonaws.com/zhcndoc-bun/icons/typescript.svg" theme={null}
export function Welcome({ name }: { name: string }) {
  return <h1>Hello, {name}!</h1>;
}
```

```bash terminal icon="terminal" theme={null}
bun run Component.tsx
```

### Extensioned imports

Import TypeScript files with their full extensions:

```ts theme={null}
import { greet } from "./greet.ts";
import { Component } from "./Component.tsx";
```

This is more explicit and aligns with browser-native ESM behavior.

### Decorators

Bun supports experimental decorators and the TypeScript 5.0+ decorator proposal:

```json tsconfig.json icon="file-json" theme={null}
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}
```

***

## Path mapping

Bun respects `paths` in `tsconfig.json` for module resolution:

```json tsconfig.json icon="file-json" theme={null}
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"],
      "@components/*": ["./src/components/*"]
    }
  }
}
```

Now you can use these path aliases:

```ts theme={null}
import { Button } from "@components/Button";
import { utils } from "@/utils";
```

***

## Type checking

Bun's runtime doesn't perform type checking—it only strips type annotations. For type checking, use the TypeScript compiler:

```bash terminal icon="terminal" theme={null}
# Type check once
bun tsc --noEmit

# Type check in watch mode
bun tsc --noEmit --watch
```

Add this as a script in your `package.json`:

```json package.json icon="file-json" theme={null}
{
  "scripts": {
    "typecheck": "tsc --noEmit"
  }
}
```

Then run:

```bash terminal icon="terminal" theme={null}
bun run typecheck
```

***

## DOM types

If you're building a browser application and need DOM types, add `"DOM"` to the `lib` array:

```json tsconfig.json icon="file-json" theme={null}
{
  "compilerOptions": {
    "lib": ["ESNext", "DOM", "DOM.Iterable"]
  }
}
```

This enables types for `document`, `window`, `HTMLElement`, and other browser APIs.

***

## Node.js types

Bun implements many Node.js APIs for compatibility. If you're using Node.js modules, you may want to install Node.js type definitions:

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

However, be aware that `@types/node` can conflict with Bun's types. Bun's types take precedence for built-in modules.

***

## Transpilation options

Configure how Bun transpiles TypeScript via `bunfig.toml`:

```toml bunfig.toml theme={null}
[runtime]
# Set the JSX factory
jsx = "react"
jsxFactory = "h"
jsxFragment = "Fragment"

# Enable TypeScript experimental decorators
experimentalDecorators = true
```

Alternatively, set these options in `tsconfig.json` and Bun will respect them:

```json tsconfig.json icon="file-json" theme={null}
{
  "compilerOptions": {
    "jsx": "react",
    "jsxFactory": "h",
    "jsxFragmentFactory": "Fragment",
    "experimentalDecorators": true
  }
}
```

***

## Type stripping

Bun strips the following TypeScript syntax during transpilation:

* Type annotations
* Interface declarations
* Type aliases
* Enums (converted to JavaScript objects)
* Namespace declarations (experimental)
* `import type` and `export type` statements
* Type-only imports/exports

### Enums

TypeScript enums are converted to JavaScript objects:

```ts theme={null}
enum Status {
  Pending,
  Success,
  Error,
}
```

Becomes:

```js theme={null}
var Status;
(function (Status) {
  Status[(Status["Pending"] = 0)] = "Pending";
  Status[(Status["Success"] = 1)] = "Success";
  Status[(Status["Error"] = 2)] = "Error";
})(Status || (Status = {}));
```

***

## Editor support

### VS Code

Install the [Bun for Visual Studio Code](https://marketplace.visualstudio.com/items?itemName=oven.bun-vscode) extension for enhanced Bun support:

* Syntax highlighting for `bunfig.toml`
* Debug support for Bun
* Run configurations for `bun run`, `bun test`, etc.

### Other editors

Most editors with TypeScript support work great with Bun:

* **IntelliJ IDEA / WebStorm**: Full TypeScript support built-in
* **Vim/Neovim**: Use `typescript-language-server` or `coc-tsserver`
* **Sublime Text**: Install the TypeScript plugin
* **Emacs**: Use `tide` or `lsp-mode` with `typescript-language-server`

***

## Compatibility with TypeScript versions

Bun's transpiler targets compatibility with the latest stable TypeScript release. Bun generally supports:

* ✅ TypeScript 5.0+ (full support)
* ✅ TypeScript 4.x (full support)
* ⚠️ TypeScript 3.x (mostly supported, but some features may not work)

***

## Migration from Node.js

If you're migrating a TypeScript project from Node.js to Bun:

<Steps>
  <Step title="Install Bun types">
    ```bash terminal icon="terminal" theme={null}
    bun add -d @types/bun
    ```
  </Step>

  <Step title="Update tsconfig.json">
    Use the [recommended configuration](#recommended-tsconfigjson) above.
  </Step>

  <Step title="Remove ts-node or tsx">
    You no longer need these packages since Bun natively runs TypeScript:

    ```bash terminal icon="terminal" theme={null}
    bun remove ts-node tsx
    ```
  </Step>

  <Step title="Update scripts">
    Replace `ts-node` or `tsx` with `bun` in your `package.json` scripts:

    ```json package.json icon="file-json" theme={null}
    {
      "scripts": {
        "start": "bun run src/index.ts", // Was: ts-node src/index.ts
        "dev": "bun --watch run src/index.ts"
      }
    }
    ```
  </Step>

  <Step title="Test your application">
    ```bash terminal icon="terminal" theme={null}
    bun run start
    ```
  </Step>
</Steps>

***

## Performance

Bun's TypeScript transpiler is significantly faster than `tsc` or `ts-node`:

* **Startup time**: Bun starts 4x faster than Node.js with `ts-node`
* **Transpilation**: Bun's transpiler is written in Zig and optimized for speed
* **No compilation step**: Run `.ts` files directly without a build step

<Note>
  For production builds, consider using `bun build` to bundle and minify your TypeScript code.
</Note>

***

## Additional resources

<CardGroup cols={2}>
  <Card icon="book-open" title="Runtime TypeScript" href="/runtime/typescript">
    Learn more about TypeScript support in Bun's runtime.
  </Card>

  <Card icon="cog" title="Transpiler API" href="/api/transpiler">
    Use Bun's transpiler programmatically in your code.
  </Card>

  <Card icon="combine" title="Bundler" href="/bundler">
    Bundle TypeScript for production with `Bun.build`.
  </Card>

  <Card icon="flask-conical" title="Testing" href="/test">
    Write TypeScript tests with Bun's test runner.
  </Card>
</CardGroup>
