添加 Zod Options 与 Description 顺序问题说明文档

This commit is contained in:
2026-01-16 22:55:41 +08:00
parent 59cc377899
commit d7354fdf49

37
readme.md Normal file
View File

@@ -0,0 +1,37 @@
# 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()` 之前调用,以保留描述信息。