Dev*_*low 10 reactjs react-hook-form zod
我有以下 zod 模式,在某些情况下,我想从模式中完全省略一个字段。我不能只是让它成为可选的。我怀疑有某种方法可以直接使用 zod 来实现。有没有办法省略字段或以某种方式预处理模式?
例如,我如何在没有此嵌套字段的情况下使用此架构。
const schema = z.object({
name: z.number(),
age: z.number(),
data: z.array(
z.object({
id: z.string().optional(),
name: z.string().nonempty().optional(),
})
)
});
const test = schema.shape.data //. ??? how can I omit the name field?
type typeTest = z.infer<typeof test>; // just data without name field
Run Code Online (Sandbox Code Playgroud)
我如何省略这个嵌套值?
Sou*_*man 16
要做的最小改变是:
const test = schema.shape.data.element.omit({ name: true }).array();
Run Code Online (Sandbox Code Playgroud)
但另一种选择是将您的架构重新组织为几个命名部分,然后将merge它们组合起来,如下所示:
import { z } from 'zod';
const dataSchema = z.object({
id: z.string().optional(),
someOtherField: z.number(),
});
const namedSchema = z.object({
name: z.string().nonempty().optional(),
});
const fullDataSchema = dataSchema.merge(namedSchema);
type Data = z.TypeOf<typeof dataSchema>;
type FullData = z.TypeOf<typeof fullDataSchema>;
Run Code Online (Sandbox Code Playgroud)
另一个选项使用omit您的基本数据模式类型来获取没有该字段的模式,然后使用typeof生成的模式。如果您想在不同的场景中使用模式,我建议给它们命名。
import { z } from 'zod';
const dataSchema = z.object({
id: z.string().optional(),
someOtherField: z.number(),
name: z.string().nonempty().optional(),
});
const noNameDataSchema = dataSchema.omit({ name: true });
type Data = z.TypeOf<typeof noNameDataSchema>;
Run Code Online (Sandbox Code Playgroud)
两种方法各有利弊,但结果应该是相同的。(我个人发现自己更频繁地执行前者,因为我发现代码更容易遵循)