Express Types in TypeScript
Express Types in TypeScript
Section titled “Express Types in TypeScript”Typed Request and Response
Section titled “Typed Request and Response”import { Request, Response, NextFunction } from 'express';
interface CreateUserDto { name: string; email: string; password: string;}
interface UserParams { id: string;}
type CreateUserRequest = Request<{}, {}, CreateUserDto>;type GetUserRequest = Request<UserParams>;
app.post('/users', (req: CreateUserRequest, res: Response) => { const { name, email } = req.body; // name and email are typed});Augmenting Express Request
Section titled “Augmenting Express Request”import 'express';
declare module 'express' { interface Request { user?: { id: string; role: string }; requestId: string; startTime: number; }}
// Now Request.user is available everywhereapp.get('/me', (req, res) => { console.log(req.user?.id); // typed!});Interview Questions
Section titled “Interview Questions”Easy: How do you type Express request parameters?
Medium: How do you augment the Express Request type?
Hard: How would you create a generic request handler type with custom DTO?