Files
test-zod/readme.md

38 lines
1.0 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Zod Options 与 Description 顺序问题说明
## 问题描述
在使用 Zod 定义 Schema 时,如果 `.options()` 方法调用位于 `.describe()` 方法之后,会导致设置的 description 信息丢失。
## 错误示例
```typescript
import { z } from "zod";
// 错误options 在 description 后面
const schema = z.object({
name: z.string().describe("用户名").options({ message: "请输入用户名" }),
});
```
在上面的示例中,`describe("用户名")` 设置的描述信息会被后续的 `.options()` 调用覆盖。
## 正确示例
```typescript
import { z } from "zod";
// 正确options 在 description 前面
const schema = z.object({
name: z.string().options({ message: "请输入用户名" }).describe("用户名"),
});
```
## 原因分析
Zod 的方法链式调用中,`.options()` 会创建新的 schema 实例,导致之前通过 `.describe()` 设置的元数据丢失。
## 建议
在 Zod Schema 定义时,应确保 `.options()``.describe()` 之前调用,以保留描述信息。