Skip to content

feat: add .invert() method to ZodCodec#5770

Open
mahmoodhamdi wants to merge 1 commit intocolinhacks:mainfrom
mahmoodhamdi:feat/codec-invert
Open

feat: add .invert() method to ZodCodec#5770
mahmoodhamdi wants to merge 1 commit intocolinhacks:mainfrom
mahmoodhamdi:feat/codec-invert

Conversation

@mahmoodhamdi
Copy link

Summary

Closes #5625

Adds an .invert() method to ZodCodec (and ZodMiniCodec) that returns a new codec with swapped input/output schemas and swapped decode/encode transforms.

Usage

const isoDateCodec = z.codec(z.iso.datetime(), z.date(), {
  decode: (isoString) => new Date(isoString),
  encode: (date) => date.toISOString(),
});

// Inverted: Date → ISO string
const dateToIso = isoDateCodec.invert();

z.decode(dateToIso, new Date("2024-01-15T10:30:00.000Z"));
// → "2024-01-15T10:30:00.000Z"

z.encode(dateToIso, "2024-01-15T10:30:00.000Z");
// → Date object

This is useful when composing schemas in pipelines where the direction needs to be flipped — for example, form validation schemas in react-hook-form where the input type is string but the output should be a parsed value.

Implementation

The method creates a new codec with:

  • def.indef.out swapped
  • def.transformdef.reverseTransform swapped

Zero runtime overhead — just a new instance with references swapped.

Files changed

  • packages/zod/src/v4/classic/schemas.tsZodCodec interface + constructor
  • packages/zod/src/v4/mini/schemas.tsZodMiniCodec interface + constructor
  • packages/zod/src/v4/classic/tests/codec.test.ts — 5 new test cases

Test plan

  • Basic invert: decode/encode directions swapped correctly
  • Round trip: invert preserves data through decode→encode cycle
  • Type inference: z.input/z.output types correctly swapped
  • Double invert: .invert().invert() behaves like original
  • Invert with pipe: works with piped schemas
  • Full test suite passes (3585 tests, 0 type errors)
  • Format and lint checks pass

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
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.

Feature Request: add .invert() method to codecs

1 participant