乐闻世界logo
搜索文章和话题

How to make an optional property with a default value in Zod

1个答案

1

In Zod, creating optional properties with default values is a common requirement, especially when handling data validation or configuring objects. Zod is a TypeScript-friendly library for building robust, type-safe validation schemas. It enables us to easily define data structures while ensuring type safety and providing default values.

To create an optional property with a default value in Zod, we can use the .optional() and .default() methods. Here is a specific example demonstrating how to define an optional property with a default value:

typescript
import { z } from 'zod'; // Define a schema that includes an optional property with a default value const PersonSchema = z.object({ name: z.string(), // required property age: z.number().optional(), // optional property with no default value isStudent: z.boolean().default(false), // optional property with a default value }); // Create an object that conforms to the schema const person = PersonSchema.parse({ name: "张三", // age property is omitted // isStudent is also omitted, but will use the default value false }); console.log(person); // Output: { name: '张三', isStudent: false } // Note that if age is not provided, it will not appear in the resulting object because it has no default value // If we provide all values const anotherPerson = PersonSchema.parse({ name: "李四", age: 25, isStudent: true, }); console.log(anotherPerson); // Output: { name: '李四', age: 25, isStudent: true }

In this example, PersonSchema defines three properties: name, age, and isStudent. Among them, name is a required string, age is an optional number, and isStudent is an optional boolean property with a default value of false.

When using the .default() method, Zod automatically marks the property as optional, so we don't need to explicitly call .optional(). If the value for isStudent is not provided during parsing, Zod will use the default value false.

By doing this, Zod not only ensures data type safety but also handles default values and optional properties, greatly simplifying data processing and validation.

2024年7月21日 19:47 回复

你的答案