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
Because we are adding a default value, we no longer need
.optional() because optional is included within it.
With this change, our test now passes.
The Input is Different than the Output
We've reached the point with Zod where our input is different than our output.
In other words, you can generate types based on input as well as generating types based on the output.
For example, let's create
As written above, the input is not quite correct because when we input into
validateFormInput, we don't need to pass in any keywords.
Instead, we can update the the
FormInput to use
z.input instead of
This gives us a way to slightly tweak the types we generate if there is a difference between the input and output of our validator.
Matt Pocock: 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.
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.
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.
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.