Skip to content

Instantly share code, notes, and snippets.

@brian-mcallister-lab49
Created June 18, 2020 19:19
Show Gist options
  • Save brian-mcallister-lab49/859e02b08517221d364e4726f05a9dd8 to your computer and use it in GitHub Desktop.
Save brian-mcallister-lab49/859e02b08517221d364e4726f05a9dd8 to your computer and use it in GitHub Desktop.
TIL-Lab49/Enforce request and response types when using express with TypeScript.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment