我的博客文章有 3 个架构。
架构看起来像这样
// will be used for form validation
// text can be added but image required
const imagePostSchema = z.object({
body: z.string().max(500).optional().or(z.literal('')),
attachmentType: z.literal('img'),
attachment: // z... image validation is here
});
// text can be added but video required
const videoPostSchema = z.object({
body: z.string().max(500).optional().or(z.literal('')),
attachmentType: z.literal('video'),
attachment: // z... video validation is here
});
// text is required & other fields must be null
const textPostSchema = z.object({
body: z.string().max(500),
attachmentType: z.null(),
attachment: z.null()
});
现在如何合并此架构以创建一个架构,以便用户可以发布任何类型的(这 3 个)帖子?
合并到接受“这 3 种中的任何类型”的模式是通过使用 ….or(…)
或
z.union(…)
的三种类型的 union来完成的。然而,由于这些类型是根据它们的
attachmentType
来区分的,所以你真的需要一个 discriminated union 这将使检查更有效:
const postSchema = z.discriminatedUnion("attachmentType", [
imagePostSchema,
videoPostSchema,
textPostSchema,
]);
要以“或”方式组合模式,请使用
z.union
。
const postSchema = z.union([imagePostSchema, videoPostSchema, textPostSchema]);
postSchema
现在对于与 3 个模式中的任何一个匹配的任何对象都有效。
您可以使用以下[z.intersection][1]
const postSchema = z.intersection( 图像后架构, 视频后架构, 文本后架构 );