Zod Section 10 exercises

Set a Default Value with Zod

Zod's .default schema method allows us to pass in a value to use if no other value is provided.

In this case, we'll set it to an empty array with .default([]).


keywords: z.array(z.string()).optional()

Loading solution


Matt Pocock: 0:00 The way to do a default in Zod is just by specifying default here. This means that you don't need to specify it's optional. You can say optional().default. What it actually means is it includes optional within it.

0:13 Now, our test is parsing because even if we parse in no keywords whatsoever, the result to keywords is always going to be this. There's something really cool about this, which is we're getting to a point with Zod now where the input is different from the output. That means that you can actually generate types based on the input and based on the output.

0:34 We can say FormInput = z.infer<typeof Form> here, and let's say we do the same with the output, then these are going to be the same. This input is not quite correct because when we input to the validate form thing, we didn't need to parse these keywords.

0:54 We can actually use z.input instead. This means that you don't need to parse them. This is a really cool way to slightly tweak the types that you're generating if you have a difference between the input to your validator and the output.