feat: add .invert() method to ZodCodec - #5770
Conversation
|
Interesting idea, but I don't think this should be a method. I'd be open to a top level |
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
Drop the codec instance method in favor of a top-level utility function. New methods on schemas raise the API surface; a free function keeps the codec interface lean and is more tree-shakable.
1599a91 to
ecd0caf
Compare
|
Pushed a follow-up that drops const dateToIso = z.invertCodec(isoDateCodec);
z.decode(dateToIso, new Date()); // → ISO string |
|
TL;DR — Adds a Key changes
Summary | 4 files | 2 commits | base: Codec inversion via
|
|
Merged — landed as a top-level Note: this comment was produced by an AI coding assistant. |
|
Landed in Zod 4.4 |
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