使用Zod与递归类型,并正确推断它们

huangapple go评论89阅读模式
英文:

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&lt;typeof barSchema&gt;;

However barSchema gives me the typescript error:

&#39;barSchema&#39; implicitly has type &#39;any&#39; 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 作为“类型提示”。

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".

Zod Docs

huangapple
  • 本文由 发表于 2023年7月14日 04:18:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76682976.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定