Typescript with Bun
Bun is a fast JavaScript runtime that’s excellent for TypeScript development. Here’s how to get started learning TypeScript using Bun:
Installation
Section titled “Installation”First, install Bun:
# Using npmnpm install -g bunSetting Up a TypeScript Project
Section titled “Setting Up a TypeScript Project”Create a new project:
mkdir my-typescript-projectcd my-typescript-projectbun initOr Install TypeScript (though Bun has built-in TS support):
bun add -d typescriptbun add -d @types/bunBasic TypeScript Example
Section titled “Basic TypeScript Example”Create a simple TypeScript file index.ts:
// Basic typeslet message: string = "Hello, TypeScript with Bun!";let count: number = 42;let isActive: boolean = true;
// Function with type annotationsfunction greet(name: string): string { return `Hello, ${name}!`;}
// Interfaceinterface User { id: number; name: string; email?: string; // Optional property}
// Using the interfaceconst user: User = { id: 1, name: "Alice"};
// Arrays and genericsconst numbers: number[] = [1, 2, 3];const users: User[] = [user];
// Run the codeconsole.log(greet("Bun User"));console.log("User:", user);Running TypeScript with Bun
Section titled “Running TypeScript with Bun”Run your TypeScript file directly:
bun run index.tsPackage.json Configuration
Section titled “Package.json Configuration”Your package.json should look like this:
{ "name": "my-typescript-project", "module": "index.ts", "type": "module", "devDependencies": { "typescript": "^5.0.0", "@types/bun": "latest" }, "peerDependencies": { "typescript": "^5.0.0" }}tsconfig.json
Section titled “tsconfig.json”Create a tsconfig.json file:
{ "compilerOptions": { "target": "ES2020", "module": "ESNext", "moduleResolution": "bundler", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true, "declaration": true, "outDir": "./dist" }, "include": ["**/*.ts"], "exclude": ["node_modules", "dist"]}Advanced Example: HTTP Server
Section titled “Advanced Example: HTTP Server”Create server.ts:
import { serve } from 'bun';
// Type for request datainterface RequestData { name?: string; email?: string;}
const server = serve({ port: 3000, async fetch(request: Request) { const url = new URL(request.url);
if (url.pathname === '/api/users' && request.method === 'POST') { try { const data: RequestData = await request.json();
if (!data.name) { return new Response( JSON.stringify({ error: 'Name is required' }), { status: 400, headers: { 'Content-Type': 'application/json' } } ); }
return new Response( JSON.stringify({ message: `User ${data.name} created successfully`, data }), { headers: { 'Content-Type': 'application/json' } } ); } catch (error) { return new Response( JSON.stringify({ error: 'Invalid JSON' }), { status: 400, headers: { 'Content-Type': 'application/json' } } ); } }
return new Response('Hello from Bun TypeScript Server!'); },});
console.log('Server running at http://localhost:3000');Run the server:
bun run server.tsTesting with TypeScript
Section titled “Testing with TypeScript”Create a test file index.test.ts:
import { expect, test } from 'bun:test';import { greet } from './index';
test('greet function works correctly', () => { expect(greet('Alice')).toBe('Hello, Alice!'); expect(greet('Bob')).toBe('Hello, Bob!');});
// Async test exampletest('async operations', async () => { const result = await Promise.resolve('async result'); expect(result).toBe('async result');});Run tests:
bun testUseful Bun Commands for TypeScript
Section titled “Useful Bun Commands for TypeScript”# Run TypeScript filebun run file.ts
# Start development server with hot reloadbun --hot server.ts
# Install TypeScript typesbun add -d @types/node
# Build projectbun build ./index.ts --outdir ./dist
# Run testsbun testKey Benefits of Using Bun with TypeScript
Section titled “Key Benefits of Using Bun with TypeScript”- Fast execution - Bun runs TypeScript natively without compilation step
- Built-in TypeScript support - No additional setup needed
- Excellent developer experience - Fast startup and hot reload
- All-in-one tool - Package manager, test runner, and bundler
Next Steps
Section titled “Next Steps”- Explore Bun’s built-in APIs for file system, HTTP, and more
- Learn about Bun’s native SQLite support
- Experiment with Bun’s plugin system
- Try building a full-stack application with Bun and TypeScript