Storing all unknown keys under an "additionalProperties" key #3541
disintegrator
started this conversation in
Ideas
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hey there, I'm posting a problem which I've attempted to solve and now I'm looking for ideas or someone to nerd snipe. It's also possible that I'm describing a feature request. Regardless, if you have a better approach then what I've come up with then I'd love to hear about it!
Problem
I have a Zod object schema like this:
The output type for this will be:
What I would like instead is to have this result:
One approach is to use a transform:
Caution
The problem with this approach is that it does not minify well especially if you have many Zod schemas that need this treatment. Those destructured keys have to stay as-is in the minified source. With esbuild, it can even be slightly larger (example).
My solution
So, I resorted to doing some meta-programming and created a helper function that can take a
ZodObject
and amend it with a.transform
to do the work above.And it's applied like this:
The modified schema now results in the desired type but I have a feeling there's a simpler approach to this problem. If not, then I propose a new feature to Zod's
.catchall
that allows specifying a key to group unrecognized fields under e.g.z.object(...).catchall(z.unknown(), "extraKeys")
.Here's a playground link to tinker with.
Beta Was this translation helpful? Give feedback.
All reactions