Why isn't my dynamically extended Zod schema enforcing types in @hono/zod-openapi?
Hey folks, I'm running into something weird with @hono/zod-openapi
I'm dynamically building a schema like this:
Then I use this in a route definition like:
And this is my route handler
The issue is: even when
channel.videos
returned by ChannelService doesn't exist or has the wrong type, no TypeScript error is shown. It only works when I use selectChannelSchema.extends outside of the if statement. Why is that and how do I properly extend my schema dynamically?13 Replies
don't build dynamic schemas
You can add two overloads to the function to fix this issue, when the videos is false, to return a specific type, when it is true, to return another type
Right now your function returns a union of those two types (?), you'll have to narrow it down
See online how typescript function overloads work, ChatGPT can help you with it as well
GeeksforGeeks
TypeScript Function Overloads - GeeksforGeeks
Your All-in-One Learning Portal: GeeksforGeeks is a comprehensive educational platform that empowers learners across domains-spanning computer science and programming, school education, upskilling, commerce, software tools, competitive exams, and more.
Notice that the overloads are merely types and not implementations, since JavaScript has polymorphism they did it that way
an overload will narrow the type if the parameters are known at compile time
In this case they are
then why use a factory at all?
Idk man, I am here to solve problems 🤣
dynamic zod schemas are an antipattern. factories can be useful in building complex schemas, but it's generally best to compose them statically and use tools like discrimination to deal with variable features
Like
Oh you meant zod discrimination
For payloads? sure
For responses? nope
why not for responses?
you'll need to discriminate client-side to access the resolved type, but you'd need to do that anyway if your endpoint returns a union
The issue is that it doesn't return a union
They have multiple routes that return a similar response, the difference being if videos exist or not
two static schemas seems like a better solution to that problem, assuming OP meant "factory" instead of "dynamic schema"
my point wasn't that discrimination specifically is the right choice for this (or any) use-case, but rather that zod provides a variety of utilities that can be used to build complex schemas statically + without mutation