Definitelytyped: @types/express request's body object to T (generic)

Created on 5 Jun 2017  ·  3Comments  ·  Source: DefinitelyTyped/DefinitelyTyped

hey there!

why not change the body of the Request to T? that way I can be sure what my object contains.

in express-serve-static-core/index.d.ts line 438:

interface Request<T> extends http.IncomingMessage, Express.Request {
...
...
body: T
...
...

and I use it like this:

updateUser = (req: Request<User>, res: Response, next: NextFunction) => {
   const userToUpdate = req.body;
...
...
}

Most helpful comment

Make sense, also I think there is a way to include this feature without breaking changes by using default generics, ex:

interfare Request<B = any, Q = any, P = any, C = any> {
  body: B;
  query: Q;
  params: P;
  cookies: C;
}

All 3 comments

Agreed, this should be changed for peoples that want to type their Request body, same should apply to cookies, params, query, @borisyankov what do you think?

I don't hate this idea, but at the same time there is this issue from types/express which explains that body was left out for a reason. That reason being that body doesn't exist on the Express Request object natively, but rather is added because of body-parser.

Unfortunately the DefinitelyTyped version of body-parser doesn't work with the workaround they proposed. So either body needs to be added here, or DefinitelyTyped/body-parser needs to be updated.

Make sense, also I think there is a way to include this feature without breaking changes by using default generics, ex:

interfare Request<B = any, Q = any, P = any, C = any> {
  body: B;
  query: Q;
  params: P;
  cookies: C;
}
Was this page helpful?
0 / 5 - 0 ratings