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('/',(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('/',(req: CustomRequest<PersoneModel>, res: Response) => { // req.body is now PersoneModel}
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;