Back to Tutorials

Building Type-Safe APIs with TypeScript

TypeScript Setup

TypeScript adds static typing to JavaScript, improving code quality and developer experience.

Type Definitions

interface User {
    id: number;
    name: string;
    email: string;
}

interface CreateUserDto {
    name: string;
    email: string;
}

Express Server with TypeScript

import express, { Request, Response } from 'express';

const app = express();
app.use(express.json());

app.get('/api/users', (req: Request, res: Response<User[]>) => {
    res.json(users);
});

app.post('/api/users', (req: Request<{}, User, CreateUserDto>, res: Response<User>) => {
    const { name, email } = req.body;
    const user: User = { id: Date.now(), name, email };
    res.status(201).json(user);
});

Best Practices

  • Define interfaces for all data structures
  • Use strict TypeScript configuration
  • Leverage type inference
  • Use generics for reusable code
  • Enable strict null checks