DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Zod - TypeScript-first schema declaration and validation library #7

Set a Default Value with Zod

Our following 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(),
})
Enter fullscreen mode Exit fullscreen mode

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

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

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

Before:

keywords: z.array(z.string()).optional()
Enter fullscreen mode Exit fullscreen mode

After:

keywords: z.array(z.string()).default([])
Enter fullscreen mode Exit fullscreen mode

Because we are adding a default value, we no longer need .optional() because optional is included within it.

const Form = z.object({
  repoName: z.string(),
  keywords: z.array(z.string()).default([])
})
Enter fullscreen mode Exit fullscreen mode

I hope you found it useful. Thanks for reading. 🙏
Let's get connected! You can find me on:

Top comments (0)