zod icon indicating copy to clipboard operation
zod copied to clipboard

Making all fields of an object "nullable"

Open AslanTaheri opened this issue 1 year ago • 3 comments

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();

AslanTaheri avatar Oct 21 '23 02:10 AslanTaheri

+1, a nullish partial would be a great feature

cjlawson02 avatar Oct 26 '23 19:10 cjlawson02

I agree and I would like to work on this feature.

cicerotcv avatar Nov 08 '23 05:11 cicerotcv

Has any progress been made here @cicerotcv? I'm happy to pick up where you left off.

wesharper avatar Mar 11 '24 06:03 wesharper

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
}

image

Hope it helps someone

acro5piano avatar Sep 04 '24 07:09 acro5piano