Search code examples
javascriptjsonzod

Zod: Create a primitive object from defaults


I'm pretty sure this exists, but I haven't been able to find anything about it despite some digging. Say that I have a zod Schema like such:

const Person = zod.object({
    name: z.string().default(''),
    age: z.number().nullable();
});

Is there a way to create something like this:

const InstancePerson = {
    name: '',
    age: null
}

from the zod Schema?


Solution

  • I know that I am a little late to the party but maybe it will help someone in the future.

    You could extend your zod schema in the following way:

    const Person = zod.object({
        name: z.string().default(''),
        age: z.number().nullable().default(null)
    }).default({}); // .default({}) could be omitted in this case but should be set in nested objects
    

    Now, you can retrieve your desired output by calling:

    const InstancePerson = Person.parse({});