ikhvjs
ikhvjs

Reputation: 5977

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

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?

Upvotes: 3

Views: 2917

Answers (1)

ikhvjs
ikhvjs

Reputation: 5977

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
}

Upvotes: 5

Related Questions