You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
> **TLDR** — You can use `z.encode(<schema>, <input>)` to perform an _encode_ operation ("reverse parsing"). This will work with any schema (except those containing `.transform()`) but is primarily intended for use in conjunction with `z.codec()`.
10
+
All Zod schemas can process inputs in both the forward and backward direction:
11
11
12
-
Zod schemas are "codecs". That is, they can process inputs in both the forward and backward direction:
12
+
-**Forward**: `Input` to `Output`
13
+
-`.parse()`
14
+
-`.decode()`
15
+
-**Backward**: `Output` to `Input`
16
+
-`.encode()`
13
17
14
-
-*Decoding*: the "forward" direction: `Input -> Output`. This is what regular `.parse()` does.
15
-
-*Encoding*: the "backward" direction: `Output -> Input`.
16
-
17
-
The regular `.parse()` method performs a *decode* operation (forward direction).
18
+
In most cases, this is a distinction without a difference. The input and output types are identical, so there's no difference between "forward" and "backward".
18
19
19
20
```ts
20
-
import*aszfrom"zod";
21
-
22
-
const mySchema =z.string();
21
+
const schema =z.string();
23
22
24
-
//method form
25
-
mySchema.parse("hello"); //=> "hello"
23
+
typeInput=z.input<typeofschema>; //string
24
+
typeOutput=z.output<typeofschema>; //string
26
25
27
-
// functional form
28
-
z.parse(mySchema, "hello"); // => "hello"
26
+
schema.parse("asdf"); // => "asdf"
27
+
schema.decode("asdf"); // => "asdf"
28
+
schema.encode("asdf"); // => "asdf"
29
29
```
30
30
31
-
For explicitness, Zod provides dedicated functions for performing "decode" and "encode" operations.
32
-
33
-
```ts
34
-
z.decode(mySchema, "hello"); // => "hello"
35
-
z.encode(mySchema, "hello"); // => "hello"
36
-
```
37
-
38
-
In many cases (such as the string schema above), the input and output types of a Zod schema are identical, so `z.decode()` and `z.encode()` are functionally equivalent. But some schema types cause the input and output types to diverge:
39
-
40
-
-`z.default()` (input is optional, output is not)
41
-
-`z.transform()` (a unidirectional transformation)
42
-
-`z.codec()` (bidirectional transformation)
43
-
44
-
Most important of these is `z.codec()`, which is Zod's primary mechanism for defining bidirectional transformations.
31
+
However, some schema types cause the input and output types to diverge, notably `z.codec()`. Codecs are a special type of schema that defines a *bi-directional transformation* between two other schemas.
45
32
46
33
```ts
47
34
const stringToDate =z.codec(
@@ -52,20 +39,17 @@ const stringToDate = z.codec(
52
39
encode: (date) =>date.toISOString(), // Date → ISO string
0 commit comments