Zod Tutorial (10 exercises)
Problem

Set a Default Value with Zod

Our next example starts similarly to the last: a form input validator that supports an optional value.

This time the Form has a repoName and an optional array of keywords:

const Form = z.object({
  repoName: z.string(),
  keywords: z.array(z.string()).optional(),
});

In order to make things easier for the actual form, we want to set this up so that an array of strings doesn't have to be passed in.

Challenge

Update the Form so that keywords will default to an empty array of strings if no strings are passed into the validator function.

Transcript

Matt Pocock: We've now got a similar problem here, which is we're validating a form input. This one is for when you create a new repository. We've got the repoName here. We've got a set of keywords, except we want to make it a little bit easier on the form here.

We want to say you didn't need to parse this array of strings for the keyword. We've made it optional here, except we don't want to have to deal with undefined or array. If they don't parse any keywords, we want it to default to an empty array. That's what our test is validating down there.

What we end up with is we've got string this or undefined, which isn't what we want really. We want it to just say if they don't parse any keywords, just default it to an empty array. Your challenge is to somehow find how you can do a default in Zod.