Sub topic 12
Reshaping Data with `transform`
This chapter assumes you know basic TypeScript types, JavaScript objects, JSON, npm imports, and try/catch. You should also understand that a Zod schema validates data at runtime, while a TypeScript type only guides code during compilation.
What `transform` does
A Zod transform changes validated data into another value. The schema validates the input first. If validation succeeds, the callback passed to transform runs and returns the parsed output.
This is useful when external data has a shape that is inconvenient inside your application. For example, an API might send a display name under name, while your application uses displayName.
import { z } from "zod";
const User = z
.object({
name: z.string().trim().min(1),
tags: z.array(z.string()).default([]),
})
.transform((value) => ({
displayName: value.name,
tags: value.tags.map((tag) => tag.trim().toLowerCase()),
}));
const user = User.parse({
name: " Ada Lovelace ",
tags: ["Math", " PROGRAMMING "],
});
console.log(user);
// { displayName: "Ada Lovelace", tags: ["math", "programming"] }The object schema checks that name is a non-empty string and that tags is an array of strings. Only after those checks does the transform rename the field and normalize the tags.
Input types and output types
A transformed schema has two useful types:
- The input type describes the value accepted by the schema.
- The output type describes the value returned by
parse.
Use z.input and z.output to access them.
type UserInput = z.input<typeof User>;
// { name: string; tags?: string[] | undefined }
type UserOutput = z.output<typeof User>;
// { displayName: string; tags: string[] }The tags field is optional in the input because it has a default. It is always present in the output. The transform also changes the field name, so name exists in the input but not in the output.
A transform can also change the value's type:
const Length = z.string().transform((value) => value.length);
const count = Length.parse("TypeScript");
console.log(count); // 10
type LengthInput = z.input<typeof Length>; // string
type LengthOutput = z.output<typeof Length>; // numberTransforming safely
Keep validation rules in the schema before the transform. This ensures that the callback receives the expected type. A transform callback should usually normalize, rename, or combine values rather than silently accept invalid input.
For rules that depend on several fields, validate them with refine before transforming. Also remember that the returned value is the transform's result. If the result needs additional validation, use another schema to validate that result explicitly.
A practical pattern
Use one schema for external input and let the parsed output become the application's trusted shape:
- Describe the incoming fields.
- Add normal validation rules.
- Transform names, formats, or collections.
- Pass only the parsed output to the rest of the application.
Exercise
What are the input and output types of z.string().transform((value) => value.length)?
Show answer
The input type is string, and the output type is number.