如何合并多个Zod(对象)模式

问题描述 投票:0回答:3

我的博客文章有 3 个架构。

  1. 图片发布
  2. 视频帖子
  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 个)帖子?

typescript zod
3个回答
5
投票

合并到接受“这 3 种中的任何类型”的模式是通过使用 ….or(…)

z.union(…)
的三种类型的
union
来完成的。然而,由于这些类型是根据它们的
attachmentType
来区分的,所以你真的需要一个 discriminated union 这将使检查更有效:

const postSchema = z.discriminatedUnion("attachmentType", [
  imagePostSchema,
  videoPostSchema,
  textPostSchema,
]);

0
投票

要以“或”方式组合模式,请使用

z.union

const postSchema = z.union([imagePostSchema, videoPostSchema, textPostSchema]);

postSchema
现在对于与 3 个模式中的任何一个匹配的任何对象都有效。


0
投票
  • 您可以使用以下[z.intersection][1]

    const postSchema = z.intersection( 图像后架构, 视频后架构, 文本后架构 );

© www.soinside.com 2019 - 2024. All rights reserved.