feat: add .invert() method to ZodCodec#5770
Open
mahmoodhamdi wants to merge 1 commit intocolinhacks:mainfrom
Open
feat: add .invert() method to ZodCodec#5770mahmoodhamdi wants to merge 1 commit intocolinhacks:mainfrom
mahmoodhamdi wants to merge 1 commit intocolinhacks:mainfrom
Conversation
Adds an .invert() method that returns a new codec with swapped input/output schemas and swapped decode/encode transforms. This enables composing codecs in either direction without manually re-declaring them. const dateToIso = isoDateCodec.invert(); z.decode(dateToIso, new Date()); // → ISO string Closes colinhacks#5625
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
Closes #5625
Adds an
.invert()method toZodCodec(andZodMiniCodec) that returns a new codec with swapped input/output schemas and swapped decode/encode transforms.Usage
This is useful when composing schemas in pipelines where the direction needs to be flipped — for example, form validation schemas in
react-hook-formwhere the input type isstringbut the output should be a parsed value.Implementation
The method creates a new codec with:
def.in↔def.outswappeddef.transform↔def.reverseTransformswappedZero runtime overhead — just a new instance with references swapped.
Files changed
packages/zod/src/v4/classic/schemas.ts—ZodCodecinterface + constructorpackages/zod/src/v4/mini/schemas.ts—ZodMiniCodecinterface + constructorpackages/zod/src/v4/classic/tests/codec.test.ts— 5 new test casesTest plan
z.input/z.outputtypes correctly swapped.invert().invert()behaves like original