Sub topic 3
Unions and Discriminated Unions
This chapter assumes basic TypeScript types, JavaScript objects and arrays, npm packages, and try/catch.
Choosing a Union
A union schema accepts one of several shapes. A discriminated union uses a shared field, such as type, to select the correct shape.
import { z } from "zod";
const Click = z.object({
type: z.literal("click"),
x: z.number(),
y: z.number(),
});
const Key = z.object({
type: z.literal("key"),
key: z.string(),
});
const Event = z.discriminatedUnion("type", [Click, Key]);
type Event = z.infer<typeof Event>;
function describe(event: Event): string {
return event.type === "click"
? `click at ${event.x},${event.y}`
: `key ${event.key}`;
}TypeScript narrows event after checking event.type. This is clearer and usually faster than testing several unrelated object schemas.
Reusing and Extending Schemas
Schema methods prevent related definitions from drifting apart.
const User = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
nickname: z.string().optional(),
});
const UpdateUser = User.pick({ name: true, nickname: true }).partial();
const PublicUser = User.omit({ id: true });
const AdminUser = User.extend({ isAdmin: z.boolean() });pick keeps fields, omit removes fields, partial makes fields optional, and extend adds fields.
Custom Rules and Transformations
Use refine for rules involving multiple fields. Use transform when valid input should become another value.
const Signup = z.object({
password: z.string().min(8),
confirm: z.string(),
}).refine((data) => data.password === data.confirm, {
message: "Passwords do not match",
path: ["confirm"],
});
const FormDate = z.string().transform((value) => new Date(value));Coercion and Input/Output Types
Environment variables and form controls usually provide strings. Coercion converts them during parsing.
const Env = z.object({
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
START_DATE: z.coerce.date(),
});
type EnvInput = z.input<typeof Env>;
type EnvOutput = z.output<typeof Env>;EnvInput accepts string-like raw values. EnvOutput contains a number and a Date.
Exercise
Exercise
Which schema should you use when every valid object has a type field identifying its shape?
Show answer
Use z.discriminatedUnion("type", schemas).