英文:
Using Zod with Recursive types and infer them properly
问题
我有这样的模式:
export const barSchema = z.object({
id: z.string(),
foo: z.object(fooSchema),
});
export const fooSchema = z.object({
id: z.string(),
bar: z.object(barSchema),
});
export type BarType = z.infer<typeof barSchema>;
但是barSchema
给我带来了TypeScript错误:
'barSchema'隐式具有类型'any',因为它没有类型注释,并且在其自己的初始化程序中直接或间接引用。
我真的想要使用类型推断的功能。我该如何解决这个问题?
英文:
I have schemas like so:
export const barSchema = z.object({
id: z.string(),
foo: z.object(fooSchema),
});
export const fooSchema = z.object({
id: z.string(),
bar: z.object(barSchema),
});
export type BarType = z.infer<typeof barSchema>;
However barSchema
gives me the typescript error:
'barSchema' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
I really want to use the ability to infer types. How can I do that and resolve the issue.
答案1
得分: 1
抱歉,根据 Zod 文档的说法,我认为你所要求的可能是不可能的。
你可以在 Zod 中定义递归模式,但由于 TypeScript 的限制,它们的类型不能被静态推断。相反,你需要手动定义类型定义,并将其提供给 Zod 作为“类型提示”。
英文:
Unfortunately, I don't think what you're asking for is possible if the Zod documentation is to be believed.
> You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint".
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论