Q48: How do you strongly type Express Request and Response objects in TypeScript?
Install @types/express and extend standard Express interfaces (Request, Response, NextFunction) to type route params, response bodies, and custom req.user properties.
Strongly Typed Express Controller in TypeScript
import { Request, Response, NextFunction } from 'express';
interface UserParams {
id: string;
}
interface UserResponseBody {
id: string;
name: string;
}
export const getUser = (
req: Request<UserParams, UserResponseBody>,
res: Response<UserResponseBody>,
next: NextFunction
) => {
const userId = req.params.id; // Strongly typed as string
res.json({ id: userId, name: 'John Doe' });
};💡 Generics provided to Request and Response interfaces supply autocompletion and type checking.
Key Takeaways
- Pass custom types into
Request<Params, ResBody, ReqBody, Query>generics. - Extend
Express.Requestnamespace globally to add custom properties likereq.user.