38 lines
1.0 KiB
Markdown
38 lines
1.0 KiB
Markdown
# 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()` 之前调用,以保留描述信息。
|