Desmoline Awa
Desmoline Awa

Reputation: 535

How to properly type-check express route handler response

How do I properly type-check function with a return like this

return res.status(200).send({ user, token });

I have an express route handler type-checked as follows:

  type AuthResponse = {
    user: typeof Subscription;
    token: string;
  }

  type ErrorResponse = { error: string }

  async signUp(req: Request, res: Response, next: NextFunction): Promise<Response<AuthResponse | ErrorResponse>> {
    try {
      return res.status(200).send({ user, token });
    } catch (error) {
      next(error)
    }
  }

However the Promise<Response<AuthResponse | ErrorResponse>> type seems to have no effect. It doesn't flag when I return a response that doesn't match the response body.

Upvotes: 1

Views: 697

Answers (1)

funkizer
funkizer

Reputation: 4897

TS compiler can't infer the type of res based on what you pass to res.send(). You need to type the res argument like this and then you will get compiler / intellisense errors if you try to send the wrong type of data:

async signUp (
  req: Request, 
  res: Response<AuthResponse>, 
  next: NextFunction
)

Upvotes: 2

Related Questions