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
JacobParis
JacobParis11mo ago
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
return NextResponse.json(schema.parse({}))
return NextResponse.json(schema.parse({}))
Liam
Liam11mo ago
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
NextResponse<z.infer<typeof myCoolValidator>>
NextResponse<z.infer<typeof myCoolValidator>>
that wouldn't be lying right? I am just not sure if this kind of type is creatable.
JacobParis
JacobParis11mo ago
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
Want results from more Discord servers?
Add your server
More Posts