Zod 模式中的 self 数组

Max*_*Max 7 node.js typescript zod

我想实现以下目标:

export const MediaResponseSchema = z.object({
    mediaId: z.number(),
    childMedias: z.array(z.object(MediaResponseSchema)),
});
Run Code Online (Sandbox Code Playgroud)

childMedia应该被解析为我声明的模式的数组。

Sou*_*man 11

我认为提到递归类型的评论是正确的,但为了充分说明其意图,您可以使用z.lazy,然后从其定义中引用架构。你的例子将变成:

import { z } from "zod";

// Zod won't be able to infer the type because it is recursive.
// if you want to infer as much as possible you could consider using a
// base schema with the non-recursive fields and then a schema just for
// the recursive parts of your schema and use `z.union` to join then together.
interface IMediaResponse {
  mediaId: number;
  childMedias: IMediaResponse[];
}

const MediaResponseSchema: z.ZodType<IMediaResponse> = z.lazy(() =>
  z.object({
    mediaId: z.number(),
    childMedias: z.array(MediaResponseSchema)
  })
);
Run Code Online (Sandbox Code Playgroud)

请参阅GitHub 上的 Zod 文档,尽管我认为这应该与链接的内容相同。

只是回应这个评论:

这和复制粘贴整个 zod 对象有什么区别?

一个关键的区别是这将无限期地递归。可以childMedia与自己的子媒体任意嵌套。如果您只是复制和粘贴,那么您最终只会增加一层递归,并且当您尝试决定将哪些内容放入childMedias粘贴的内容时,您会遇到与开始时相同的问题。

  • 感谢您的彻底回答。但遗憾的是,Zod/TS 无法推断,因为我的模式包含数百行,并且有 5 层深,因此将模式代码复制到接口中非常麻烦。 (2认同)