Normalize arbitrary input
Convert values from multiple runtime types into one representation.
Zod · Function
z.transform() creates a unidirectional Zod schema that accepts any input and maps it to a new output through a callback. Use it with pipes when validation must precede transformation.
z.transform() creates a schema whose callback receives the input and returns the transformed output. Unlike a normal validating schema, it accepts any input; use .pipe() when validation must happen before transformation. The callback should report validation problems through its context rather than throwing exceptions.
z.transform((value, ctx) => output)| Name | Type | Description |
|---|---|---|
transform | (value, ctx) => output | A callback receiving the input value and returning its transformed value; the documentation also describes a context for registering issues. |
A Zod schema representing the transformed output.
z.transform() to build a schema that maps input values in one direction.String produces a string for every input.z.encode().import { z } from "zod";
const toText = z.transform((value) => String(value));
console.log(toText.parse(123));
console.log(toText.parse(true));Creates a schema that converts any parsed input to text.
Convert values from multiple runtime types into one representation.
Validate a value before changing its shape or type.
Build a one-way parsing pipeline for application data.
z.transform() do?z.transform() creates a unidirectional schema transformation. It accepts any input and applies the callback, so z.transform(value => String(value)) turns numbers and booleans into strings.
Follow-up: How would you validate before converting? Pipe a validating schema into the transform, such as z.string().pipe(z.transform(value => value.length)).
The callback should not throw because Zod does not catch exceptions thrown by transform functions. If the callback needs to signal invalid data, it should use the provided context to add an issue.
Follow-up: What is the practical distinction between a thrown exception and an added issue? An added issue participates in Zod's normal validation result, while a thrown exception escapes parsing.
Transforms are unidirectional: they map parsed input to output but do not define a reverse conversion. Consequently, a schema containing a transform cannot be used with z.encode() successfully.
Follow-up: What abstraction is appropriate for reversible conversion? Use a codec, which defines separate decode and encode transformations between schemas.
z.pipez.codecz.encodez.safeParse