javascriptnode.jstypescriptzod

Switch programmatically a property nullish or optional to required in Zod


I'm working with objects in Zod. Let's say I have a base schema.

const baseSchema = z.object({
  id: z.string(),
  date: z.string().pipe(z.coerce.date()).optional(),
  free: z.boolean().optional(),
  paymentMethod: z.string().optional(),
  // many more properties below...
});

Now I need to define a second zod object based on the first one, but changing its properties. For example switch some optional to nullish (and viceversa), or switch a field optional/nullish to required.

What I don't want is to copy the entire object and paste it into a new zod schema and change manually every single property I need.

Is there any way I could do this with an inheritance behaviour in which I could modify certain properties from the base schema?


Solution

  • Yes you can, by using the .extend() method of zod, let's see how:

    This is your baseChema.

    const baseSchema = z.object({
      id: z.string(),
      date: z.string().pipe(z.coerce.date()).optional(),
      free: z.boolean().optional(),
      paymentMethod: z.string().optional(),
    });
    

    And now, this is the extended one, inheriting properties when you don't write them, and modifying the ones you specified:

    const newSchema = baseSchema.extend({
      date: z.string().pipe(z.coerce.date()).nullable(), 
      paymentMethod: z.string().required()
    });
    

    You can also check other methods like pick() or omit().