Back to Blog Posts
EY

GYBEX

@gybex_enock

2 min read

Zod's Default And Catch Methods

  • #zod
  • #typescript
Zod's Default And Catch Methods

Zod is a powerful, flexible, and easy-to-use validation library that provides a simple and expressive syntax for defining validation schemas in TypeScript and JavaScript. One of its key features is the ability to handle default values and exceptions. In this blog post, we will discuss the differences between .default and .catch methods in Zod.

Zod .default Method

The .default method in Zod allows us to provide a default value for a field in our schema. This method is particularly useful when we want to ensure that a certain field always receives a value, even if none is provided in the input data. This is achieved by passing the desired default value to the .default method. If the input is undefined, the default value is returned; otherwise, the data is parsed using the base schema.

import { z } from 'zod'; const enumWithDefault = z.enum(['Admin', 'Guest', 'User']).default('Guest'); enumWithDefault.parse(undefined); // => "Guest" enumWithDefault.parse('Admins'); // => throws an Error enumWithDefault.parse(0); // => throws an Error

Using .default is fine when the user does not provide the value or explicitly sets the value to undefined. However, if the user provides a value that does not conform to the schema (in this case, either of 'Admin', 'Guest', 'User'), an error is thrown. Let's look at how the .catch method can come in handy in this scenario.

Zod .catch Method

Similar to the .default method, this feature enables us to set a default value for a field in our schema. However, it differs slightly from the .default method when the user provides a value that does not match the schema. Rather than triggering an error, it gracefully defaults to the fallback value.

import { z } from 'zod'; const enumWithCatch = z.enum(['Admin', 'Guest', 'User']).catch('Guest'); enumWithCatch.parse(undefined); // => "Guest" enumWithCatch.parse('Admins'); // => "Guest" enumWithCatch.parse(0); // => "Guest"

Conclusion

In instances where validation requires a default value, the .catch method is particularly useful. Be sure to use the right one that fits your project's needs.

Thank you for reading and Happy Coding!