Skip to content

fix: apply default values for missing tuple elements#5661

Open
Cyjin-jani wants to merge 2 commits intocolinhacks:mainfrom
Cyjin-jani:fix/5229-tuple-default-values
Open

fix: apply default values for missing tuple elements#5661
Cyjin-jani wants to merge 2 commits intocolinhacks:mainfrom
Cyjin-jani:fix/5229-tuple-default-values

Conversation

@Cyjin-jani
Copy link

Summary

Fixes #5229

When parsing tuples with missing trailing elements that have .default() values, the default values were not being applied. Instead, the elements were simply skipped.

Before (As-is)

const myTuple = z.tuple([z.string(), z.string().default('bravo')]);
myTuple.parse(['alpha']); // => ['alpha'] (default ignored)

After (To-be)

const myTuple = z.tuple([z.string(), z.string().default('bravo')]);
myTuple.parse(['alpha']); // => ['alpha', 'bravo'] (default applied)

Changes

Modified the tuple parsing logic to run the schema for default type elements even when the input array is shorter, allowing $ZodDefault to apply its default value.
File: packages/zod/src/v4/core/schemas.ts

- if (i >= input.length) if (i >= optStart) continue;
+ if (i >= input.length && i >= optStart && item._zod.def.type !== "default") continue;

Test Plan

✅ Added test case for tuple with default elements in tuple.test.ts
✅ All existing tests pass

Verified Issue Examples

All examples from #5229 now work correctly:

// Example 1: Basic tuple with default
z.tuple([z.string(), z.string().default('bravo')]).parse(['alpha']);
// ✅ Now returns: ['alpha', 'bravo']

// Example 2: Skipped - this correctly throws an error (expected behavior, not a bug)

// Example 3: ZodFunction with correct API
z.function().input([z.string(), z.string().default('bravo')])
.implement((name, company) => console.log(name, company));
// ✅ Now logs: "alpha bravo"

// Example 4: Destructuring
const [name, company] = z.tuple([z.string(), z.string().default('bravo')]).parse(['alpha']);
// ✅ Now: name = "alpha", company = "bravo"

Copy link
Contributor

@pullfrog pullfrog bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Medium priority — The fix correctly addresses the reported issue for .default() but misses .prefault(), which has identical default-providing semantics. This is a real edge case that users could hit.

Pullfrog  | Fix all ➔Fix 👍s ➔View workflow runpullfrog.com𝕏

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.

Tuple Ignoring Default Values

1 participant