fix: optionality handling in zodv4 Properties type#1521
Open
Dqu1J wants to merge 1 commit into
Open
Conversation
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.
Issue
With the
zodv4schema the generated schemas fail to typecheck with their optional field types degrading tounknown. The issue is in thePropertiestype:In Zod v4,
z.objectdetermines whether a key is optional by checking the field schema's internaloptoutflag.Currently the
Propertiestype defines every field as a plainZodType, which doesn't have that flag set, so optionality can't be inferred. That causes optional fields to degrade tounknown.Fix
The
Propertiestype has been changed as follows:Optional fields (those that can be
undefined) get their ZodType intersected with{ _zod: { optout: "optional" } }, which sets theoptoutflag to mark the field as optional to Zod. That letsz.objectinfer the correct optionality.Required<>is needed because otherwise the type's?would be carried over to the schema itself, making it possibly undefined, which breaksz.object's inference and causes the field to degrade tounknown.While
_zodandoptoutis Zod's internal API, it seems to be stable and recommended to use by maintainers.Testing
pnpm run testwith and without changes, number of passed tests match.Closes #1494
Closes #1460