Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 908
Dragonsnap Avatar asked Jan 24 '26 14:01

Dragonsnap


1 Answers

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({});
like image 192
ChaRioteer Avatar answered Jan 27 '26 04:01

ChaRioteer



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!