Search code examples
typescriptzod

How can I type a helper function for Zod, which wraps the object and default functions?


I want to create a helper function for use in my project that uses Zod. The function will accept the arguments that the Zod function object expects, and then returns a Zod object with the default function also applied.

All the fields passed to the Zod object will have a default function applied (I understand this is a bit fragile, but this function is for internal use only), so the arguments to default will be simply .default({})

The function looks like this:

const c = (shape: any, params?: any) => z.object(shape, params).default({});

Obviously, I need to type shape and params correctly, using generics, but I find the typing of the functions in Zod very complicated.


Solution

  • It has been a while but I think I did something similar a few years ago.

    import { z, ZodObject } from 'zod';
    
    const createZodObject = <S extends z.ZodRawShape>(shape: S): ZodObject<S> => {
      const zodObject = z.object(shape);
      return zodObject.default({});
    };
    
    
    const obj = createZodObject({
      name: z.string(),
      age: z.number(),
    });
    

    This solution (function) only takes a single generic parameter S representing the shape of the object being passed in. It then creates a Zod object with the specified shape and applies the default function.