zod
zod copied to clipboard
Making all fields of an object "nullable"
Currently, it is possible to make an object's properties optional by using .Partial
. However, this does NOT make the object properties nullable, so there would be a repetitive task of adding nullable()
to every field as seen below. Could we have an option to make all fields all 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();
+1, a nullish partial would be a great feature
I agree and I would like to work on this feature.
Has any progress been made here @cicerotcv? I'm happy to pick up where you left off.
An userland workaround is like this:
export type NullableObjectReturn<T extends z.ZodRawShape> = z.ZodObject<
{ [k in keyof T]: z.ZodNullable<T[k]> },
z.UnknownKeysParam,
z.ZodTypeAny
>
export function nullableObject<T extends z.ZodRawShape>(
obj: z.ZodObject<T>,
): NullableObjectReturn<T> {
const newShape: any = {}
keys(obj.shape).forEach((key) => {
const fieldSchema = obj.shape[key]
newShape[key] = fieldSchema.nullish()
})
return new z.ZodObject({
...(obj.shape._def as any),
shape: () => newShape,
}) as any
}
Hope it helps someone