Skip to content

Conversation

@NathanKneT
Copy link

Fix recursive tuple infinite recursion regression (#5089)

Problem

Recursive tuples that worked in Zod v3 throw TypeError: Cannot read properties of undefined (reading '_zod') in v4 during schema initialization.

Root Cause

$ZodLazy and $ZodReadonly constructors access properties on potentially uninitialized schemas during circular reference scenarios.

Solution

  • Add optional chaining (?.) for safe property access in lazy getters
  • Minimal change preserving performance and architecture
  • No breaking changes to existing functionality

Changes

  • src/v4/core/schemas.ts: Add optional chaining to property access in $ZodLazy and $ZodReadonly constructors
  • src/v4/core/tests/recursive-tuples.test.ts: Comprehensive regression test suite

Testing

  • ✅ All existing tests pass
  • ✅ New tests cover recursive tuple patterns from the issue
  • ✅ Verifies both schema creation and parsing work correctly
  • ✅ Maintains backward compatibility

Before/After

Before (broken):

const y = z.lazy((): any => z.tuple([y, y]).or(z.string()));
y.parse(["a", ["b", "c"]]); // TypeError: Cannot read properties of undefined

…s#5089)

- Add optional chaining to $ZodLazy and $ZodReadonly property access
- Prevents "Cannot read properties of undefined (reading '_zod')" errors
- Add regression tests for recursive tuple patterns
- Maintains backward compatibility and performance

Fixes colinhacks#5089
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant