Home > Software engineering >  How to make TypeScript type annotation for res.body without overwriting the original Request in Expr
How to make TypeScript type annotation for res.body without overwriting the original Request in Expr

Time:04-16

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 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?

CodePudding user response:

You can import ParamsDictionary from 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
}
  • Related