Zod Tutorial (10 exercises)

Make Schemas Optional

The solution is really intuitive in this case!

By adding .optional() on to the end of our phoneNumber schema, our test will pass:

const Form = z.object({ name: z.string(), phoneNumber: z.string().optional(), });

What we are saying here is that name is a string, and phoneNumber is either a string or undefined.

We don't have to parse anything, making this a really nice way to set a property as optional.


Matt Pocock: Luckily, Zod makes this really, really intuitive with .optional here. Now you can see inside the test that it is all working. What we end up with is a type that looks like...If we go type FormType = z.infer typeof Form, then what we get is name is now a string, but phoneNumber is now a string or undefined. You don't have to parse it, which is really, really nice. That's just a really simple addition you can add if you need a property to be optional.