Skip to content

Commit 1fc9f31

Browse files
committed
docs: document codec inversion
1 parent 292c894 commit 1fc9f31

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

packages/docs/content/api.mdx

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2564,6 +2564,15 @@ To perform the *reverse transform*, use the inverse: `z.encode()`.
25642564
z.encode(stringToDate, new Date("2024-01-15")); // => "2024-01-15T00:00:00.000Z"
25652565
```
25662566

2567+
Use `z.invertCodec()` to derive a new codec with the input and output schemas swapped.
2568+
2569+
```ts
2570+
const dateToString = z.invertCodec(stringToDate);
2571+
2572+
z.decode(dateToString, new Date("2024-01-15")); // => string
2573+
z.encode(dateToString, "2024-01-15T00:00:00.000Z"); // => Date
2574+
```
2575+
25672576
Refer to the dedicated [Codecs](/codecs) page for more information. That page contains implementations for commonly-needed codecs that you can copy/paste into your project:
25682577

25692578
- [**`stringToNumber`**](/codecs#stringtonumber)

packages/docs/content/codecs.mdx

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,37 @@ This is particularly useful when parsing data at a network boundary. You can sha
9292
alt="Codecs encoding and decoding data across a network boundary"
9393
/>
9494

95+
### Inverting codecs
96+
97+
Use `z.invertCodec()` to derive the reverse codec from an existing one. The returned codec swaps the input and output schemas, then swaps the `decode` and `encode` transforms.
98+
99+
<Tabs items={['Zod', 'Zod Mini']}>
100+
<Tab value="Zod">
101+
```ts
102+
const dateToString = z.invertCodec(stringToDate);
103+
104+
dateToString.decode(new Date("2024-01-15T10:30:00.000Z"));
105+
// => string
106+
107+
dateToString.encode("2024-01-15T10:30:00.000Z");
108+
// => Date
109+
```
110+
</Tab>
111+
<Tab value="Zod Mini">
112+
```ts
113+
const dateToString = z.invertCodec(stringToDate);
114+
115+
z.decode(dateToString, new Date("2024-01-15T10:30:00.000Z"));
116+
// => string
117+
118+
z.encode(dateToString, "2024-01-15T10:30:00.000Z");
119+
// => Date
120+
```
121+
</Tab>
122+
</Tabs>
123+
124+
`z.invertCodec()` only inverts the codec you pass to it. It does not recursively invert codecs nested inside another schema; invert those codecs where you define the reversed schema.
125+
95126
### Composability
96127

97128
> **Note** — You can use `z.encode()` and `z.decode()` with any schema. It doesn't have to be a ZodCodec.

0 commit comments

Comments
 (0)