Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zod object schema with nullable fields

Tags:

zod

typescript

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();
like image 675
Aslan Avatar asked Oct 16 '25 21:10

Aslan


1 Answers

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()
  }),
)
like image 179
ehsaneha Avatar answered Oct 19 '25 11:10

ehsaneha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!