Type Express request params and body
Pass type arguments to an Express route for params, response body and request body, so req.params.id and req.body.name are typed. Express 5.
In an untyped handler, req.body is any. The route methods in @types/express take type arguments for each part of the exchange.
import express from 'express';
type Params = { id: string };
type Body = { name: string };
type Reply = { id: string; name: string };
const app = express();
app.use(express.json());
app.put<Params, Reply, Body>('/users/:id', (req, res) => {
res.json({ id: req.params.id, name: req.body.name });
});
app.listen(3000);$ curl -X PUT localhost:3000/users/7 -H 'content-type: application/json' -d '{"name":"Ada"}'
{"id":"7","name":"Ada"}The three type arguments are the route parameters, the response body and the request body. With them req.params.id is a string, req.body.name is a string, and res.json accepts only a Reply, so a typo in the response is a compile error. The order comes from the Request generic in the [@types/express-serve-static-core](https://www.npmjs.com/package/@types/express-serve-static-core) package.
These types are a claim, not a check. Express does not validate the body: a client can send {} and req.body.name is undefined at runtime. In Express 5, req.body is also undefined when no body parser matched. Validate with a schema at the edge, then rely on the type.