You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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):
exportasyncfunctionPOST(request: Request): Response{constbody=awaitrequest.json();// ^? const body: any ❌returnnewResponse(JSON.stringify({abc: 123,// ❌ how can the POST function return type check this object?}))}
What would be amazing would be something similar to this:
typeRequestBody={zzz: number};typeResponseBody={abc: number};exportasyncfunctionPOST(request: Request<RequestBody>): Response<ResponseBody>{constbody=awaitrequest.json();// ^? const body: { zzz: number } ✅returnnewResponse(JSON.stringify({abc: 123,// ✅ type checked}))}
Workaround
Response
Wasn't able to find a nice workaround for typing the body of a Response yet.
Similar to the
FormData
request by @wesbos in microsoft/TypeScript#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:
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
is unknown until runtime, so maybe this should be handled instead with Zod or some other runtime validationThe text was updated successfully, but these errors were encountered: