RPC types not working with imported Zod Object
Hi,
When using Hono with RPC for inferring types on endpoints I have encountered a strange behaviour. Post payload & return types are working if I use z.object(), but not an imported z.object() (I call it TestSchema in the example below). I don't want to redefine types in two places, is there any way I can have an imported Zod Object in zValidator that gets inferred to the client with RPC?
This works:
Results in this on client
This doesnt work:
Results in this on client
Thanks in advance
10 Replies
that should work
do you have access to the validated payload in the
post handler?@ambergristle Yes, the payload has correctly inferred types on the backend in the post handler. And it works to send data thru from client > backend succesfully. It is only that the types aren't shown in the client.
roughly how many routes do you have? and what's your project setup? monorepo?
@ambergristle Yes, monorepo (only with two "apps", Hono backend and Next.js frontend) with pnpm workspaces. I don't know if its related to a tsconfig file or similar? Not many routes at all, I am just getting started with this project, maybe 10.
are you importing the generated types (
d.ts files), or just typeof app?@ambergristle I export it like this
and import it like this, and construct an api client
first step is probably to switch to using generated types. even if that doesn't fix the problem, it will preempt type issues as you scale
this may also be helpful: https://hono.dev/docs/guides/rpc#compile-your-code-before-using-it-recommended
@ambergristle I'll try to swith to generated types, I'll let you know if it helped thx
@ambergristle Generated types seemed to do the trick. I don't quite know why, but I'll guess I would've switched to that either way sooner or later. Thanks for your help
think about it this way. when you do
every time your TS server wants to figure out what
AppType is, it essentially recalculates from scratch, which means going down every route tree, through every validation schema, etc.
when you try to do that import across projects, it becomes even more complex
wheras generated types are static -> no computation. they just are whatever they need to beYeah I get that it is slower, I just thought it would work albeit slower. But seems like it is slower and didnt even work for some nested types. But I guess all good now 🙂