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

rob*_*ash 5 typescript zod

我使用 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>;
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

有没有办法给 Zod 提供类型,以便它在 ie VS Code 中显示嵌套类型名称而不是类型的结构?(仅使用类型或接口时就像这样)

在此输入图像描述

我想避免同时编写类型模式。

提前致谢!

Sou*_*man 5

当您推断 的类型时myWrapperSchemazod正在查看所有子字段的类型。因此,它基本上是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>;
Run Code Online (Sandbox Code Playgroud)

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

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>;
Run Code Online (Sandbox Code Playgroud)