Schema Manipulation
on this page
Each schema has some manipulation methods such as making them optional, providing default values, etc. Lets take a look at a few of them.
Optional
We can make a particular schema optional. Doing so will make it accept undefined as a valid value too.
const personSchema = z.object({
name : z.string(),
address : z.string().optional()
})
personSchema.parse({name : 'john'}) //passes
personSchema.parse({name : 'john', address : "UK" }) //passes
It should be noted that the inferred type of person.address in this case would be string | undefined.
Default
Often times you would want to make a value optional but want to provide a default/fallback value. Heres how you can achieve that in Zod.
const userSchema = z.object({
name : z.string(),
role : z.enum(["standard", "moderator", "admin"]).default("standard")
});
userSchema.parse({name : 'john'}) // {name : 'john', role : 'standard'}
Object Pick
We can also pick certain attributes from a Zod Object schema.
const personSchema = z.object({
name : z.string(),
address : z.string(),
income : z.number()
})
const subsetSchema = personSchema.pick(['name', 'income']);
pick returns an object schema too. In the above example, it returns an object schema having the name and income schemas.
Object Omit
The Omit method is similar to pick. Where Pick only includes the specified attributes, Omit will keep the rest, and exclude the specified ones.
const personSchema = z.object({
id : z.number(),
name : z.string(),
address : z.string(),
income : z.number()
})
const subsetSchema = personSchema.omit(['id']);
The above example will return a schema object containing the name, address, and income schemas.
Object Merge
The Merge method can be used to merge two Object schemas into a single schema. It could be used to inherit or extend an existing schema.
const animal = z.object({
id : z.number(),
name : z.string()
});
const dog = z.object({
breed : z.string()
}).merge(animal);
The resulting dog schema will have id, name, and breed attributes.