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 use this function below. it makes all of the fields of the zod object nullable and also preserves the field types.
function nullable<TSchema extends z.AnyZodObject>(schema: TSchema) {
const entries = Object.entries(schema.shape) as [keyof TSchema['shape'], z.ZodTypeAny][];
const newProps = entries.reduce((acc, [key, value]) => {
acc[key] = value.nullable();
return acc;
}, {} as {
[key in keyof TSchema['shape']]: z.ZodNullable<TSchema['shape'][key]>
});
return z.object(newProps)
}
usage:
nullable(
z.object({
field1: z.string(),
field2: z.number()
}),
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With