Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[libdom] Allow Response / Request to be generics #174456

Closed
karlhorky opened this issue Feb 15, 2023 · 1 comment
Closed

[libdom] Allow Response / Request to be generics #174456

karlhorky opened this issue Feb 15, 2023 · 1 comment

Comments

@karlhorky
Copy link

karlhorky commented Feb 15, 2023

Similar to the FormData request by @wesbos in microsoft/TypeScript#43797, it would be great if the Request and Response 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):

export async function POST(request: Request): Response {
  const body = await request.json();
     // ^? const body: any ❌
  return new Response(JSON.stringify({
    abc: 123, // ❌ how can the POST function return type check this object?
  }))
}

What would be amazing would be something similar to this:

type RequestBody = { zzz: number };
type ResponseBody = { abc: number };

export async function POST(request: Request<RequestBody>): Response<ResponseBody> {
  const body = await request.json();
     // ^? const body: { zzz: number } ✅
  return new Response(JSON.stringify({
    abc: 123, // ✅ type checked
  }))
}

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:

type RequestBody = { zzz: string };

export async function POST(request: Request) {
  const body = await request.json() as RequestBody;

Caveats

  1. Arguably, the Request is unknown until runtime, so maybe this should be handled instead with Zod or some other runtime validation
@karlhorky
Copy link
Author

Oops, somehow reported this in the wrong repo, moved over here: microsoft/TypeScript#52777

@github-actions github-actions bot locked and limited conversation to collaborators Apr 1, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant