[FIXED] How to make TypeScript type annotation for req.body without overwriting the original Request Type in Express?

Issue

I can do something like below to set the type of req.body to PersoneModel.

import { Request, Response } from 'express';

router.post('/',(req: Request<{}, any, PersoneModel>, res: Response) => {
   // req.body is now PersoneModel
}

However, I overwrite the original Request Type such as P extends core.Params = core.ParamsDictionary shown below.

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

How do I avoid this?

Solution

You can import ParamsDictionary from express-serve-static-core like below.

import { ParamsDictionary } from "express-serve-static-core";
import { Request, Response } from 'express';


router.post('/',(req: Request<ParamsDictionary, any, PersoneModel>, res: Response) => {
   // req.body is now PersoneModel
}

Answered By – ikhvjs

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published