如何让Zod在VS Code中显示嵌套类型名称而非结构?
让Zod推断的类型在VS Code中显示嵌套类型名称
我使用Zod定义Schema并从中推断类型,习惯为嵌套对象单独定义Schema,例如为content属性定义myObjectSchema:
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推断的类型在VS Code中显示为嵌套结构(content会展开成{id: string; message: string}),我希望能像直接使用类型或接口那样显示嵌套类型名称(即content: MyObject),同时不想重复编写类型和Schema,请问是否有实现方法?
你可以通过将嵌套Schema断言为对应的推断类型的Zod类型,让VS Code的类型提示优先显示类型别名而非展开的结构,而且不需要重复编写类型和Schema。
修改后的代码示例:
import { z } from "zod"; const myObjectSchema = z.object({ id: z.string(), message: z.string(), }); export type MyObject = z.infer<typeof myObjectSchema>; const myWrapperSchema = z.object({ id: z.string(), // 给myObjectSchema加类型断言,绑定到MyObject类型 content: myObjectSchema as z.ZodType<MyObject>, }); export type MyWrapper = z.infer<typeof myWrapperSchema>;
现在查看MyWrapper的类型时,content就会显示为MyObject,而不是展开的结构,全程只需要维护Schema,类型完全自动推断。
另外还有一种方式是用z.custom复用验证逻辑,效果一致:
import { z } from "zod"; 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: z.custom<MyObject>((val) => myObjectSchema.safeParse(val).success), }); export type MyWrapper = z.infer<typeof myWrapperSchema>;
不过断言的方式更简洁,推荐优先使用第一种。
内容的提问来源于stack exchange,提问作者robbash
相关产品推荐
相关产品推荐

