Add Generic To Response in Next
Hi, I am trying to type my return with
NextResponse.json()
in a next js API route. Any idea how I can do this? Thanks!3 Replies
With any static typing you're lying to the code anyway, so best is an explicit assertion
NextResponse.json() as Type
If you want runtime safety, you can use Zod to validate the type
Yep, I am already using zod. I just want to try and catch any footguns as early as possible (and can't use TRPC in this project). If I set the return type to some kind of that wouldn't be lying right? I am just not sure if this kind of type is creatable.
If you trust your backend code and know it will be that type, then that's ok
but if there's a chance things could get out of sync (basically: that zod validator hasn't already parsed this output) then you could end up where Typescript says it's ok but it isn't and it will fail at runtime
In general, if the response cannot infer from its own body what the type is going to be, you won't be able to pass it a type and expect that to be guaranteed either