我使用Zod定义模式并从模式推断类型。每当我嵌套对象时,我更喜欢定义一个新模式,比如用于myObjectSchema属性的content。
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代码,而不是类型的结构?(就像这样,只使用类型或接口)

我希望避免同时编写类型和模式。
提前感谢!
发布于 2022-10-17 01:48:47
当您推断myWrapperSchema的类型时,zod正在查看所有子字段的类型。因此,它基本上是在您的z.infer内部执行另一个myObjectSchema,不会看到您给该类型命名的好名字。
有一种方法可以将命名类型转换为MyWrapper类型,但它涉及显式地指定myObjectSchema的类型:
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>;有一种方法可以与所有类型一起推断名称,但我觉得有点不对:
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>;https://stackoverflow.com/questions/74068609
复制相似问题