Skip to content

Instantly share code, notes, and snippets.

@pmn4
Created September 20, 2023 19:31
Show Gist options
  • Save pmn4/ae6e1bd10a0ef8c6d97f16b3500eaad6 to your computer and use it in GitHub Desktop.
Save pmn4/ae6e1bd10a0ef8c6d97f16b3500eaad6 to your computer and use it in GitHub Desktop.
Why is the NextApiResponse type generic, but `NextApiRequest` is not?
// Add type safety to NextApiRequest
type TypedNextApiRequest<Q, B> = Omit<NextApiRequest, 'body' | 'query'> & {
// make req.query have the keys we expect, but AsQuery will turn the values
// into strings or string arrays. Partial is there because you never know
// whether the request will be well-formed
query: Partial<AsQuery<Q>>;
// make req.body have the keys and value types we expect, however, know that
// the data will be deserialized from JSON, so, for example, Dates will be
// strings. again Partial is there to enforce defensive code
body: Partial<Deserialized<B>>;
};
@pmn4
Copy link
Author

pmn4 commented Sep 20, 2023

this is one of the first types I add to any @vercel #nextjs project. Using it ensures that authors of server routes declare the inputs the handler expects, making client-side code easier to write.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment