Back to Tutorials

Building Type-Safe APIs with TypeScript and Express

Why TypeScript?

TypeScript adds static typing to JavaScript, catching errors at compile time and improving code quality.

Type Definitions

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

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

TypeScript Express Server

import express, { Request, Response } from 'express';
import { User, CreateUserDto } from './types/User';

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

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

Benefits

  • Type safety catches errors early
  • Better IDE autocomplete
  • Self-documenting code
  • Easier refactoring