首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Zod:在IDE中显示推断的嵌套类型

Zod:在IDE中显示推断的嵌套类型
EN

Stack Overflow用户
提问于 2022-10-14 11:35:28
回答 1查看 144关注 0票数 1

我使用Zod定义模式并从模式推断类型。每当我嵌套对象时,我更喜欢定义一个新模式,比如用于myObjectSchema属性的content

代码语言:javascript
复制
const myObjectSchema = z.object({
  id: z.string(),
  message: z.string(),
});
export type MyObject = z.infer<typeof myObjectSchema>;

const myWrapperSchema = z.object({
  id: z.string(),
  content: myObjectSchema,
});
export type MyWrapper = z.infer<typeof myWrapperSchema>;

Zod (至少在默认情况下)返回嵌套结构。

是否有一种方法给Zod类型,以便它将显示嵌套类型名称,即VS代码,而不是类型的结构?(就像这样,只使用类型或接口)

我希望避免同时编写类型和模式。

提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2022-10-17 01:48:47

当您推断myWrapperSchema的类型时,zod正在查看所有子字段的类型。因此,它基本上是在您的z.infer内部执行另一个myObjectSchema,不会看到您给该类型命名的好名字。

有一种方法可以将命名类型转换为MyWrapper类型,但它涉及显式地指定myObjectSchema的类型:

代码语言:javascript
复制
import { z } from "zod";

interface MyObject {
  id: string;
  message: string;
}
// Here, I'm telling zod that the schema should parse this type
// so there is a named type but it comes at the cost of being
// explicit in the code.
const myObjectSchema: z.ZodType<MyObject> = z.object({
  id: z.string(),
  message: z.string()
});

const myWrapperSchema = z.object({
  id: z.string(),
  content: myObjectSchema,
});

type MyWrapper = z.infer<typeof myWrapperSchema>;

有一种方法可以与所有类型一起推断名称,但我觉得有点不对:

代码语言:javascript
复制
import { z } from "zod";

const myObjectSchema = z.object({
  id: z.string(),
  message: z.string()
});
// If I instead use a `type` alias, typescript seems to inline
// the definition, so instead I'm using an interface.
interface MyObject extends z.infer<typeof myObjectSchema> {}
// I make an alias schema as well, to give it the type I just inferred
// above and assign it to itself.
const myObjectAlias: z.ZodType<MyObject> = myObjectSchema;

const myWrapperSchema = z.object({
  id: z.string(),
  content: myObjectAlias,
});

// Here the type will show as MyObject
type MyWrapper = z.infer<typeof myWrapperSchema>;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74068609

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档