I want to define a Zod schema where all the properties are nullable. Currently I'm defining it as below, and repeating the nullable() for every property. Is there a better way of doing this without repetition?
PS. For those who suggest using .Partial
: it does NOT make object fields nullable.
const MyObjectSchema = z
.object({
p1: z.string().nullable(),
p2: z.number().nullable(),
p3: z.boolean().nullable(),
p4: z.date().nullable(),
p5: z.symbol().nullable(),
})
.partial();
You can make use of the partial method or deepPartial method on the object.
In the case above, you only need the partial method because you're not dealing with nested structures.
If you were dealing with a nested object, using partial or deepPartial depends on you, as seen below.
For both the partial and deepPartial method, the location field will be optional. But using the partial method or deepPartial method depends on whether or not you want the houseNo and country fields to be required when the location field is provided.
Note: It is also possible to make only selected fields optional