Sub topic 12
Reshaping data with transform
This chapter assumes you can define object schemas, call parse and safeParse, and read z.infer types. It also assumes you know the difference between input and output shapes, though the next chapter treats that difference formally.
Why validated data often needs reshaping
Valid data is not always in the form your program wants. A date arrives as an ISO string, but you want a Date. A tag list arrives as "a, b, c", but you want ["a", "b", "c"]. An API returns snake_case keys, but your code uses camelCase.
You could validate first and convert afterward in separate code. That splits one decision across two places, and the conversion code can run on data nobody checked. Zod's .transform() keeps both steps in the schema: it validates the input, then runs your function on the validated value, and the parsed result is the function's return value.
The basic transform
.transform(fn) takes a function that receives the already-validated value and returns the new value.
import { z } from "zod";
const WordCount = z.string().transform((text) => text.trim().split(/\s+/).length);
console.log(WordCount.parse(" one two three "));
// 3
console.log(WordCount.safeParse(42).success);
// falseThe schema still rejects anything that is not a string. The function never sees a number, so inside it text is safely typed as string. The type returned by z.infer (the output type) is number.
Transforms run only after validation passes
The order matters. If the base schema fails, Zod records the issue and skips the transform. This is why you can write transforms without defensive checks for the wrong type.
The same ordering applies to chained methods. Each step receives the output of the step before it.
import { z } from "zod";
const Tags = z
.string()
.min(1, "Provide at least one tag")
.transform((raw) => raw.split(",").map((tag) => tag.trim()))
.transform((tags) => tags.filter((tag) => tag.length > 0));
console.log(Tags.parse("zod, typescript, ,runtime"));
// [ 'zod', 'typescript', 'runtime' ]The first transform produces a string[], so the second one receives a string[]. Splitting into small steps keeps each function easy to test.
Built-in string transforms
For common cases you do not need a custom function. Zod's string schema has trim(), toLowerCase(), and toUpperCase(), and these also work as transforms in the pipeline.
import { z } from "zod";
const Email = z.string().trim().toLowerCase().min(3);
console.log(Email.parse(" [email protected] "));
// [email protected]Because trim() runs before min(3), a string of only spaces fails the length check. Order your checks and conversions deliberately.
Reporting problems from inside a transform
Sometimes the conversion itself can fail. A string can be valid as text yet not parse as a date. A transform receives a second argument, ctx, so it can add an issue instead of throwing an exception. Return z.NEVER afterward to tell TypeScript the function produces no usable value.
import { z } from "zod";
const IsoDate = z.string().transform((value, ctx) => {
const date = new Date(value);
if (Number.isNaN(date.getTime())) {
ctx.addIssue({ code: "custom", message: "Not a valid date" });
return z.NEVER;
}
return date;
});
const ok = IsoDate.safeParse("2026-11-25T15:31:06Z");
if (ok.success) {
console.log(ok.data.getUTCFullYear());
// 2026
}
const bad = IsoDate.safeParse("next Tuesday");
if (!bad.success) {
console.log(bad.error.issues[0].message);
// Not a valid date
}An issue added this way appears in error.issues like any built-in failure, with the correct path when the schema sits inside an object. If you instead let the function throw, the exception escapes safeParse and defeats its purpose. Always report problems through ctx.
Transforming whole objects
A transform on an object schema receives the validated object. This is a good place to rename keys or compute derived fields.
import { z } from "zod";
const ApiUser = z
.object({
user_id: z.number().int(),
first_name: z.string(),
last_name: z.string(),
})
.transform((raw) => ({
id: raw.user_id,
firstName: raw.first_name,
lastName: raw.last_name,
fullName: `${raw.first_name} ${raw.last_name}`,
}));
type User = z.infer<typeof ApiUser>;
// { id: number; firstName: string; lastName: string; fullName: string }
const user: User = ApiUser.parse({
user_id: 7,
first_name: "Ada",
last_name: "Lovelace",
});
console.log(user.fullName);
// Ada LovelaceThe transform sits at the edge of your program, so the rest of the code works only with the camelCase shape and never sees the wire format.
Chaining into another schema with pipe
A transform can produce a value that needs further validation. A string like "42" can become a number, but you may still want to check that the number is an integer in a range. Use .pipe() to feed the transform's output into a second schema.
import { z } from "zod";
const PageNumber = z
.string()
.regex(/^\d+$/, "Digits only")
.transform(Number)
.pipe(z.number().int().min(1).max(500));
console.log(PageNumber.parse("12"));
// 12
console.log(PageNumber.safeParse("900").success);
// falseThe first stage guarantees the text contains only digits. The second stage checks the numeric range on the converted value. Without pipe, you would have to re-check the number by hand inside the transform.
Transforms and the other pieces
Transforms interact with features from earlier chapters in a few ways you should know.
| Feature | Behavior with transform |
|---|---|
| `.refine()` placed after a transform | Receives the transformed value, so it checks the output. |
| `.refine()` placed before a transform | Receives the pre-transform value, so it checks the input. |
| `.default()` | The default value is supplied before the transform, so it flows through it. |
| `.optional()` | Wrap the transformed schema, or `undefined` skips the transform. |
| `z.coerce.*` | Converts a primitive type before checks. Prefer it for plain string-to-number conversions. |
Choose z.coerce for simple type conversion and transform when the conversion has your own logic, such as splitting, renaming, or building a computed value.
Gotchas
- Output type differs from input type. After a transform, the schema accepts one type and produces another.
z.infergives you the output type. The next chapter coversz.inputandz.outputfor naming both sides. - Transforms are one-way. A schema cannot turn the output back into the input. If you need to serialize data again, write a separate function or schema for that direction.
- Compose before you transform. In Zod 3, a transformed schema is no longer an object schema, so
pick,omit,extend, andpartialare not available on it. Build the object shape with those methods first and add.transform()last. Doing this in that order is safe in Zod 4 as well. - Keep transforms pure and fast. A transform may run once per parse, including for every item in an array. Avoid network calls and side effects.
- Async work needs
parseAsync. If a transform function isasync, callparseAsyncorsafeParseAsync. Plainparsethrows when it meets an async step.
import { z } from "zod";
const Slug = z.string().transform(async (title) => {
await Promise.resolve(); // stand-in for an async lookup
return title.toLowerCase().replace(/\s+/g, "-");
});
Slug.parseAsync("Hello Zod World").then((slug) => console.log(slug));
// hello-zod-worldQuick checklist
- Validate the raw shape first, and let the transform assume it is correct.
- Report conversion failures with
ctx.addIssueandz.NEVER. - Use
.pipe()when the converted value needs more checks. - Apply
.transform()afterextend,pick,omit, andpartial. - Read the result type with
z.infer, which is the output type.
Exercise
Write a schema called Price that accepts a string such as "$12.50", strips the leading dollar sign, converts the rest to a number of cents (1250), and rejects anything that is not a dollar amount with one or two decimal places. What does Price.parse("$12.50") return, and where should the failure for "12.50" be reported?
Show answer
Use a regex check first, then a transform, for example z.string().regex(/^\$\d+(\.\d{1,2})?$/, "Expected a dollar amount").transform((s) => Math.round(parseFloat(s.slice(1)) * 100)). Price.parse("$12.50") returns 1250. The string "12.50" has no dollar sign, so the regex check fails and records an issue with the message "Expected a dollar amount" in error.issues. The transform is skipped because validation did not pass, so no conversion code runs on bad input.
Exercise
A transform calls new Date(value) and returns it directly. What goes wrong when value is "not a date", and how do you fix it so safeParse still returns a result object?
Show answer
new Date("not a date") does not throw. It returns an invalid Date whose getTime() is NaN, so the bad value passes through as if it were valid. Fix it by taking ctx as the second argument, checking Number.isNaN(date.getTime()), calling ctx.addIssue({ code: "custom", message: "Not a valid date" }), and returning z.NEVER. Then safeParse returns success: false with the issue in error.issues.