Coercion and conversion
Convert loosely typed input into a target representation, such as turning arbitrary values into strings.
Zod · Module
z.transform() creates a standalone, unidirectional schema that accepts any input and maps it to a new output. Use it with z.pipe() or .transform() when input validation should precede the conversion.
z.transform() creates a standalone schema whose callback receives any input and returns transformed output. It is unidirectional: it does not validate by itself, so combine it with z.pipe() or a schema’s .transform() method when validation should happen first; validation issues inside the callback are reported through ctx.issues.
z.transform((value, ctx) => output)| Name | Type | Description |
|---|---|---|
callback | (value: unknown, ctx: TransformContext) => output | The callback receives the input value and returns the transformed output; it may also use a context object to add issues. |
A Zod transform schema whose parsed output is the callback’s return value.
z.transform(callback), where the callback returns the desired output..transform() method is a convenience for piping that schema into a transformation.import * as z from "zod";
const toNumber = z.pipe(
z.string(),
z.transform((value) => Number(value)),
);
console.log(toNumber.parse("42")); // 42The pipeline first accepts a string and then transforms it into a number.
Convert loosely typed input into a target representation, such as turning arbitrary values into strings.
Run a checked schema first and then produce a different output type.
Reject values from inside a conversion callback by recording issues on the transform context.
z.transform() do?z.transform() defines a standalone transformation schema. It accepts any input and applies the callback, such as converting 12 to "12"; it does not perform input validation on its own.
Follow-up: How would you validate before transforming? Use z.pipe(inputSchema, z.transform(callback)), or call .transform() on the input schema.
The callback can receive a context object for validation logic. To reject the value, add an issue to ctx.issues rather than throwing, after which parsing reports the validation failure.
Follow-up: Why should the callback avoid exceptions? Zod does not catch thrown errors, so they escape as ordinary runtime exceptions rather than becoming Zod errors.
Transforms are unidirectional: they map parsed input to output but do not define a reverse encoding operation. Consequently, any transform in a schema causes z.encode() to throw at runtime.
Follow-up: What is the practical implication for schema tooling? Transform output is a black box and therefore cannot be soundly represented as JSON Schema.
z.pipez.stringz.encode.transform.overwriteZodTransformZodPipe