Bun Type Definitions

1.3.12 · active · verified Sun Apr 19

Bun-types provides comprehensive TypeScript type definitions for the Bun JavaScript runtime, currently stable at version 1.3.12. This package is crucial for developers leveraging TypeScript with Bun, offering robust static type checking, autocompletion, and improved developer experience across Bun's unique APIs and global objects. It releases frequently, typically coinciding with major and minor Bun runtime releases, ensuring type definitions remain in sync with the rapidly evolving runtime. Unlike traditional `@types/` packages that target third-party libraries, `bun-types` directly defines the core Bun runtime environment, including its native module system (e.g., `bun:sqlite`, `bun:jsc`), global APIs like `Bun.serve` and `Bun.file`, and Web API implementations (e.g., `fetch`, `Request`, `Response`). Its key differentiator is its tight integration and direct support for Bun's opinionated, high-performance ecosystem, providing an authoritative and up-to-date type experience that reflects Bun's specific behaviors and extensions.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates a basic HTTP server using Bun's native `Bun.serve` API, showcasing type safety and core functionality.

import type { ServeOptions, Server } from "bun";

const port = process.env.PORT ?? 3000;

const serverOptions: ServeOptions = {
  port: Number(port),
  async fetch(request: Request): Promise<Response> {
    const url = new URL(request.url);
    if (url.pathname === "/") {
      return new Response("Hello from Bun!", { status: 200 });
    }
    if (url.pathname === "/json") {
      return Response.json({ message: "Hello JSON!", timestamp: Date.now() });
    }
    if (url.pathname === "/delay") {
      await Bun.sleep(1000); // Bun-specific sleep function
      return new Response("Delayed response!", { status: 200 });
    }
    return new Response("Not Found", { status: 404 });
  },
  error(error: Error): Response {
    console.error("Server error:", error);
    return new Response(`Error: ${error.message}`, { status: 500 });
  }
};

const server: Server = Bun.serve(serverOptions);

console.log(`Bun server running on http://localhost:${server.port}`);
console.log(`Server PID: ${server.pid}`);

// Gracefully shut down the server on process termination signals
process.on("SIGINT", () => {
  console.log("Shutting down server...");
  server.stop();
  console.log("Server stopped.");
  process.exit(0);
});

// To run this example: bun run your_file_name.ts

view raw JSON →