Open karlhorky opened 1 year ago
IMO the same reason applies here: https://github.com/microsoft/TypeScript/issues/33037#issuecomment-524384825
Same thing why JSON.parse()
is not generic.
JSON.parse()
is only one part of the equation - the parsed request body. That is why I wrote the caveat in the issue above:
- Arguably, the
Request
body is unknown until runtime, so this is better handled instead with Zod or some other runtime validation. But for quick/simple projects without this validation, it's nice to be able to type the request body type.
Type checking the return value of a function (the Response
part of this proposal) is a statically analyzable way to enforce the response shapes of API handlers (eg. especially useful with the new Response.json()
static method) and does not have anything to do with the "JSON data off the wire" mentioned in your linked comment.
@karlhorky You might like this. (I saw you on my TypedFormData package! :) I build a very small wrapper around fetch, Request and Response for this particular issues :) Ofc it's fully compatible with regular interfaces. You can check it out here! https://github.com/k1eu/typed-request
Suggestion
🔍 Search Terms
request, response, libdom, generic, generics, type parameters
✅ Viability Checklist
My suggestion meets these guidelines:
⭐ Suggestion
Similar to the
FormData
request by @wesbos in https://github.com/microsoft/TypeScript/issues/43797, it would be great if theRequest
andResponse
globals could also accept generic type parameters.This will become more relevant as more frameworks continue to increase their usage of these standard globals, also in Node.js.
Consider the following example of an App Route handler in Next.js (handling a
POST
request to an API route):What would be amazing would be something similar to this:
📃 Motivating Example
The second example in the Suggestion section above.
💻 Use Cases
For typing the response body of API routes
Prior Art
@types/express
:Request
andResponse
types - which both accept a generic type parameter.Workaround
Response
Wasn't able to find a nice workaround for typing the body of a
Response
yet.Request
Using Type Assertion / casting via
as
:Caveats
Request
body is unknown until runtime, so this is better handled instead with Zod or some other runtime validation. But for quick/simple projects without this validation, it's nice to be able to type the request body type.