Course contentsShow
← TypeScript
Lesson 1529 of 1,79635. TypeScript with Framework Cross-ReferencesFree lesson

Request and Response Types in Express

Understanding Express.Request, Express.Response, and how to type route handlers with basic generics.

Request and Response Types in Express

What you'll learn: How to properly type Express route handlers using Express.Request, Express.Response, and basic generics to catch errors at compile-time.

The Untyped Express Problem

When you use Express without TypeScript types, req and res are essentially any, meaning you lose all type safety. You could access req.body.nonexistentField or call res.nonexistentMethod() without any compiler warnings.

Using Express Types

Express provides type definitions through @types/express. The core types you'll use are:

  • Express.Request – The incoming HTTP request object
  • Express.Response – The outgoing HTTP response object
  • Express.NextFunction – The middleware continuation function

Here's how you type a basic route handler:

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

const app = express();

app.get('/users', (req: Request, res: Response) => {
  // req and res are now typed
  res.json({ users: [] });
});

Adding Generics for Request Body and Params

Express types accept generic type parameters to specify the shape of route params, request body, and query strings:

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

app.post('/users', (req: Request<{}, {}, User>, res: Response) => {
  const userName = req.body.name; // TypeScript knows this is a string
  const userEmail = req.body.email; // Also typed as string
  
  res.status(201).json({ success: true });
});

The generic signature is: Request<Params, ResBody, ReqBody, ReqQuery>

For route parameters:

interface UserParams {
  id: string;
}

app.get('/users/:id', (req: Request<UserParams>, res: Response) => {
  const userId = req.params.id; // Typed as string
  res.json({ id: userId });
});

The Basic Pattern

Think of Express types as containers you can customize with generics. By default, they're generic and loose. You fill in the specific shapes your route expects, and TypeScript enforces those shapes throughout your handler.

Key Takeaway: Use Request<Params, ResBody, ReqBody, ReqQuery> and Response with generics to make Express routes type-safe, catching mistakes like typos in req.body or req.params at compile-time instead of runtime.