Replies: 2 comments
-
|
Zod (v4) does not provide a built-in method like For example: const constantsSchema = z.object({
a: z.string().default("defaultA"),
b: z.number().default(0),
});
const schema = z.strictObject({
constants: constantsSchema.default(constantsSchema.parse({})),
});This will ensure that if There is no native method chaining alternative (such as 📚 Sources: Have another question? Just tag @inkeep. |
Beta Was this translation helpful? Give feedback.
-
The whole point of opening the discussion was to discuss whether it would be a good idea to have a native solution for this. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Let me try to explain what behavior I'd like to implement
Consider this schema:
This would parse
{ constants: { } }as{ constants: { a: "defaultA", b: 0 } }.But if constants is empty, you might as well leave out
constantsentirely. Neveretheless, parsing{}will yield an error (as is expected), but if none of the properties on the lower level are defined, requiring the user to pass an empty object does not make a lot of sense.What you don't want to do is repeating all the defaults, while setting a default on the constants object.
Repeating yourself can be avoided if you define your constantsSchema first:
which to me lacks readability.
So I created a helper function
that can be used like this:
but since method chaining is how zod works, I was hoping that maybe in a future version, something like this could be possible (there is probably a way better name):
Beta Was this translation helpful? Give feedback.
All reactions