fix: cascade inner field defaults through .default({}) on objects#5768
Open
mahmoodhamdi wants to merge 1 commit intocolinhacks:mainfrom
Open
fix: cascade inner field defaults through .default({}) on objects#5768mahmoodhamdi wants to merge 1 commit intocolinhacks:mainfrom
mahmoodhamdi wants to merge 1 commit intocolinhacks:mainfrom
Conversation
When .default({}) is called on an object schema, the default value is
now parsed through the inner schema at definition time so that nested
field-level defaults are applied. This ensures the invariant that
schema.default(d).parse(undefined) === schema.parse(d) holds for
object schemas.
Fixes colinhacks#5764
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Fixes #5764
When
.default({})is called on an object schema, the default value is now parsed through the inner schema at definition time so that nested field-level defaults are applied. This ensures the invariant:holds for object schemas, matching user expectations and Zod v4's own direction on defaults.
Before
After
Approach
In the
_default()factory (classic, mini, and core), when the inner type is an object schema and the default is a static plain object (not a function), run it through the inner schema's parse at definition time. This:$ZodDefault.parseis preserved.default({})is called)Files changed
packages/zod/src/v4/classic/schemas.ts— classic_default()factorypackages/zod/src/v4/mini/schemas.ts— mini_default()factorypackages/zod/src/v4/core/api.ts— core_default()factorypackages/zod/src/v4/classic/tests/default.test.ts— 4 new test casesTest plan
default.test.tstests still pass (20/20)