express
exports Request
and Response
types for your request and response objects when handling express requests. It's done this for a while, but I recently learned that these types accept generics, which allow you get more specific about what you're accepting and responding with.
As the most simple possible example, let's imagine a RESTful API that responds with JSON:
router.get('/users', async (req, res, next) => {
try {
const users = await Users.getAll();
res.status(200).json(users);
} catch (err) {
next(err);
}
});
Pretty standard. But, you can take this a step further by doing:
import { Request, Response, NextFunction } from 'express';
router.get('/users', async (req: Request, res: Response<User[]>, next: NextFunction) => {
So now, if you do something like:
const resp = {
success: true,
users,
};
res.status(200).send(resp);
You'll get an error, because the object you're responding with is not User[]
, as specified in the type argument in Response
.