Zod Section 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 or

Loading exercise

Transcript

Matt Pocock: 0:00 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.

0:16 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.

0:37 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.