I want to define an object schema with Zod.js and use it to ensure that whatever input value I send to the parse method, the output object will be filled with default values when
- the value is missing in the input,
- the value is of wrong type.
For example let’s have a schema for a Person:
const PersonSchema = z.object({
address: z.object({
street: z.string().default('Trafalgar Square'),
city: z.string().default('London'),
}).default({}),
});
const person = PersonSchema.parse({});
This works nicely when address is missing. But when it is of wrong type, the parsing fails. I tried to use the catch method, but then I have to duplicate the default values in adress:
const PersonSchema = z.object({
address: z.object({
street: z.string().default('Trafalgar Square'),
city: z.string().default('London'),
}).default({}).catch({ street: 'Trafalgar Square', city: 'London' }),
});
This is totally impractical for larger data structures. Is there a way to do this with Zod? Or maybe some of the other input validation libraries can do this?