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.
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
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With