Created
September 20, 2023 19:31
-
-
Save pmn4/ae6e1bd10a0ef8c6d97f16b3500eaad6 to your computer and use it in GitHub Desktop.
Why is the NextApiResponse type generic, but `NextApiRequest` is not?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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>>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.