zod: Recursive type: Type instantiation is excessively deep and possibly infinite.

I’m running into a problem creating a parser for a fairly simple recursive type. The following errors with Type instantiation is excessively deep and possibly infinite. TS2589:

type V = [V] | "Null"

const V : z.ZodSchema<V> = z.lazy(() =>
  z.union([
    z.tuple([V]),
    z.literal("Null")
]))

However a loosely similar type works fine:

interface V {
  a: [V]
}

const V : z.ZodSchema<V> = z.lazy(() => 
  z.object({
    a: z.tuple([V])
  })
)

The use of the Tuple is significant, using an array works fine for both.

I’d be willing to work on a pr but I had a poke around and didn’t get far in finding out what causes this, if you have any tips on what might be causing it I can take another look.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 4
  • Comments: 15 (2 by maintainers)

Most upvoted comments

@takahash

This sounds similar to an issue where you might have two different versions of zod installed? Are you exporting C into a different project that might have a different version of zod also declared?

A similar error occurs when TypeScript version is 4.3 or higher.

const C = z.object({
  foo: z.string(),
  bar: z.number().optional(),
})
utils/validations/schema.ts:4:11 - error TS2589: Type instantiation is excessively deep and possibly infinite.
4 const C = z.object({
            ~~~~~~~~~~
5   foo: z.string(),
  ~~~~~~~~~~~~~~~~~~
6   bar: z.number(),
  ~~~~~~~~~~~~~~~~~~
7 })
  ~~

I’m using TypeScrip version 4.1.5 now because I don’t get this error with the version. Next.js recommends TypeScript version 4.3.2 or higher, so if anyone knows how to avoid this error, please let me know.

Deleting and re-installing node_modules worked for me

For people that use a pnpm monorepo like me, you can use PNPM Catalogs to use the same zod version for all monorepo packages without duplication the version number. After making this adjustment, deleting all node_modules folders and running pnpm i, the zod issue was fixed.

Image

This sounds similar to an issue where you might have two different versions of zod installed? Are you exporting C into a different project that might have a different version of zod also declared?

So this is the issue. I was working in a monorepo. My shared package had a different version of zod than the one installed in my next.js package. When I upgraded to the same versions in both packages, the issue was fixed.

@mhm13dev I thought I was going nuts 😅 I extracted some code from one monorepo package into its own package to be published to NPM later. And within that new package the code worked fine, but other packages using it gave me this type inference issues.

So glad I finally bumped into this 🙌