Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript type annotation for res.body

I'm using typescript for my app node.js express. I would like say the res.body is type personne. I have tried this:

router.post('/',(req: Request, res: Response) => {
   const defunt:PersoneModel = res.(<PersoneModel>body);
}

I have this model:

export type PersoneModel = mongoose.Document & {
  nom: String,
  prenom: String,
}

Can you help me?

Thank you.

like image 379
Michel Lammens Avatar asked Dec 29 '17 19:12

Michel Lammens


2 Answers

Update:

As of @types/[email protected], 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('/',(req: Request<{}, {}, PersoneModel>, res: Response) => {
   // req.body is now PersoneModel
}

For @types/[email protected] 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('/',(req: CustomRequest<PersoneModel>, res: Response) => {
   // req.body is now PersoneModel
}
like image 71
onoya Avatar answered Nov 10 '22 00:11

onoya


We can use as. This should be enough to imply that res.body is PersoneModel

 const defunt = res.body as PersoneModel;

However more straightforward way is declaring type of the variable as a PersoneModel

 const defunt: PersoneModel = res.body;
like image 22
gokcand Avatar answered Nov 10 '22 01:11

gokcand