Lesson 2 of 8
Typed Express - Request, Response & Router
Express is typed through `@types/express`. Its `Request` and `Response` are generic - `Request<Params, ResBody, ReqBody, Query>`. Understanding these generics lets you type route handlers, middleware, and error handlers precisely - and catch parameter mismatches before the server runs.
Typed Express Routes - Full Generic Usage
import express, { Router, Request, Response, NextFunction } from "express";
// ── Route handler generics: Request<Params, ResBody, ReqBody, QueryString> ──
// GET /tasks/:id - typed route params
interface TaskParams { id: string; } // route params are always strings
const router: Router = Router();
router.get(
"/tasks/:id",
async (
req: Request<TaskParams>,
res: Response<Task | { error: string }>,
next: NextFunction,
) => {
const id = parseInt(req.params.id, 10);
if (isNaN(id)) {
res.status(400).json({ error: "Invalid task ID" });
return;
}
try {
const task = await taskService.findById(id);
if (!task) {
res.status(404).json({ error: `Task ${id} not found` });
return;
}
res.json(task);
} catch (error) {
next(error); // pass to error handler
}
}
);
// POST /tasks - typed request body
interface CreateTaskBody {
title: string;
priority: "low" | "medium" | "high" | "critical";
}
router.post(
"/tasks",
async (
req: Request<{}, Task | { error: string }, CreateTaskBody>,
res: Response<Task | { error: string }>,
) => {
const { title, priority } = req.body;
if (!title || typeof title !== "string") {
res.status(400).json({ error: "title is required" });
return;
}
const created = await taskService.create({ title, priority });
res.status(201).json(created);
}
);
// GET /tasks?status=todo&page=1 - typed query string
interface TaskQuery {
status?: TaskStatus;
priority?: Priority;
page?: string; // query params are always strings
limit?: string;
}
router.get(
"/tasks",
async (
req: Request<{}, Task[] | { error: string }, {}, TaskQuery>,
res: Response<Task[] | { error: string }>,
) => {
const page = parseInt(req.query.page ?? "1", 10);
const limit = parseInt(req.query.limit ?? "20", 10);
const tasks = await taskService.findAll({ status: req.query.status, page, limit });
res.json(tasks);
}
);Common Mistakes
- Not parsing route params as numbers - route params are always `string` in Express regardless of URL pattern. Always `parseInt(req.params.id, 10)` and validate with `isNaN`.
- Setting `Response` generic to a wide type - `Response<any>` defeats the purpose. Use discriminated unions for success and error responses: `Response<Task | { error: string }>`.
- Calling `res.json()` after `res.json()` - once you call `res.json()` or `res.send()`, the response is sent. A second call causes 'Cannot set headers after they are sent.' Always `return` immediately after sending a response.
Tip
Tip
Practice Typed Express Request Response Router in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Typed Express - Request, Response & Router
Practice Task
Note
Practice Task - (1) Write a working example of Typed Express Request Response Router from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Typed Express Request Response Router is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready typescript code.
Key Takeaways
- Express is typed through `@types/express`.
- Not parsing route params as numbers - route params are always `string` in Express regardless of URL pattern. Always `parseInt(req.params.id, 10)` and validate with `isNaN`.
- Setting `Response` generic to a wide type - `Response<any>` defeats the purpose. Use discriminated unions for success and error responses: `Response<Task | { error: string }>`.
- Calling `res.json()` after `res.json()` - once you call `res.json()` or `res.send()`, the response is sent. A second call causes 'Cannot set headers after they are sent.' Always `return` immediately after sending a response.
Finished this lesson?