Code Reference

Transforms

Zod · Reference cheat sheet

Transforms

Zod · Reference cheat sheet


📋 Overview

Transforms change values during parsing: trim strings, normalize casing, map DTOs, or convert types. Output types can differ from input types.

🔧 Core concepts

APIRole
.transform(fn)Map value after validation
.pipe(schema)Feed output into another schema
z.preprocessRun before validation
Input vs outputz.input<typeof S> / z.output<typeof S>
UseExample
Normalizetrim + lowercase email
Defaultsfill missing fields
DTO mappingrename keys

💡 Examples

Trim email:

const Email = z
  .string()
  .trim()
  .toLowerCase()
  .email();

Transform shape:

const Raw = z.object({ user_id: z.string() }).transform((d) => ({
  userId: d.user_id,
}));

Pipe:

const IsoDate = z.string().datetime().pipe(z.coerce.date());

⚠️ Pitfalls

  • Transforms run on success path — failed refinements skip later transforms.
  • Inferred z.infer is the output type; use z.input when typing forms that submit raw values.
  • Overusing preprocess can hide invalid data instead of failing loudly.

On this page