Course contentsShow
← TypeScript
Lesson 1290 of 1,79630. Type-Safe APIsFree lesson

Default Values and Transformations

Apply .default() for missing values and .transform() to coerce or reshape data during validation.

Default Values and Transformations

What you'll learn: How to use .default() to handle missing values and .transform() to reshape data during Zod validation.

Handling Missing Data with .default()

When validating external data, some fields might be optional but you'd still like a predictable fallback value. Zod's .default() method lets you specify what value to use when a field is missing or undefined:

import { z } from 'zod';

const userSchema = z.object({
  name: z.string(),
  role: z.string().default('guest'),
  notifications: z.boolean().default(true)
});

const user1 = userSchema.parse({ name: 'Alice' });
// Result: { name: 'Alice', role: 'guest', notifications: true }

const user2 = userSchema.parse({ 
  name: 'Bob', 
  role: 'admin' 
});
// Result: { name: 'Bob', role: 'admin', notifications: true }

The .default() method only applies when the value is undefined — it won't replace null or other values.

Reshaping Data with .transform()

Sometimes the data you receive needs to be coerced or reformatted. The .transform() method lets you modify validated data:

const emailSchema = z.string()
  .email()
  .transform(email => email.toLowerCase());

const result = emailSchema.parse('User@Example.COM');
// Result: 'user@example.com'

const timestampSchema = z.string()
  .transform(str => new Date(str));

const date = timestampSchema.parse('2024-01-15');
// Result: Date object

You can combine both for powerful data normalization:

const configSchema = z.object({
  port: z.string()
    .default('3000')
    .transform(val => parseInt(val, 10)),
  host: z.string()
    .default('localhost')
    .transform(val => val.toLowerCase())
});

const config = configSchema.parse({});
// Result: { port: 3000, host: 'localhost' }

Key Takeaway: Use .default() to provide fallback values for missing fields, and .transform() to coerce or normalize data shapes during validation, ensuring your parsed data matches your application's exact needs.