TypeScript type annotation for res.body

Update:

As of @types/express@4.17.2, the Request type uses generics.

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/express/index.d.ts#L107

interface Request<P extends core.Params = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query> extends core.Request<P, ResBody, ReqBody, ReqQuery> { }

You could set the type of req.body to PersoneModel like this:

import { Request, Response } from 'express';

router.post("https://stackoverflow.com/",(req: Request<{}, {}, PersoneModel>, res: Response) => {
   // req.body is now PersoneModel
}

For @types/express@4.17.1 and below

Encountered similar problem and I solved it using generics:

import { Request, Response } from 'express';

interface PersoneModel extends mongoose.Document {
  nom: String,
  prenom: String,
}

interface CustomRequest<T> extends Request {
  body: T
}

router.post("https://stackoverflow.com/",(req: CustomRequest<PersoneModel>, res: Response) => {
   // req.body is now PersoneModel
}

Leave a Comment