Express with TypeScript
In this page:
Installing Express Types
Installing @types/express alongside the express package itself is required for TypeScript to understand Express's API, since Express is written in plain JavaScript with its types published separately.
Example: Installing Express Types
// npm install express
// npm install --save-dev @types/express
console.log("@types/express provides Express's type definitions");
Creating an Express App
Creating an Express app with express() returns a typed Express application instance, giving methods like .get(), .use(), and .listen() full type-checking on the callbacks and options you pass them.
Example: Creating an Express App
// import express, { Express } from "express";
// const app: Express = express();
// app.listen(3000);
console.log("express() returns a typed Express application instance");
Typed Route Handlers
Typed route handlers receive Request and Response parameters from @types/express, exposing typed access to things like req.params and res.json() instead of leaving them as untyped any.
Example: Typed Route Handlers
// import { Request, Response } from "express";
// app.get("/users/:id", (req: Request, res: Response) => {
// res.json({ id: req.params.id });
// });
console.log("Route handlers get typed Request/Response parameters");
Typed Request Data
Typing request data — like req.body or req.query — often needs an explicit generic or interface, since Express's default types only know the shape of the request object itself, not what your specific route expects to receive.
Example: Typed Request Data
interface CreateUserBody {
name: string;
}
// app.post("/users", (req: Request<{}, {}, CreateUserBody>, res: Response) => {
// console.log(req.body.name);
// });
console.log("req.body typed via an explicit generic/interface");
Typed Middleware
Typed middleware functions follow Express's (req, res, next) signature typed against Request, Response, and NextFunction, ensuring a middleware that forgets to call next() or misuses the response is caught before runtime.
Example: Typed Middleware
// import { Request, Response, NextFunction } from "express";
// function logger(req: Request, res: Response, next: NextFunction) {
// console.log(req.method, req.url);
// next();
// }
console.log("Middleware typed against Request, Response, NextFunction");
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: