Zod Cheatsheet
Zod is a TypeScript-first validation library that gives you runtime safety and static type inference with zero dependencies.
Zod is a TypeScript-first schema declaration and validation library. With Zod, you define validation schemas using TypeScript types, and get automatic static type inference as well as runtime validation. It’s perfect for validating input data while ensuring strong typing across your TypeScript application.
Basic Validation
Define basic schemas for primitive types.
const stringSchema = z.string(); // Validates strings
const numberSchema = z.number(); // Validates numbers
Required Fields
By default, fields are required.
const userSchema = z.object({
name: z.string(),
age: z.number(),
});
Optional Fields
Use .optional() to define optional fields.
const userSchema = z.object({
name: z.string(),
age: z.number().optional(),
});
Default Values
Use .default() to set default values.
const userSchema = z.object({
name: z.string(),
age: z.number().default(18),
});
Nested Objects
Schemas can contain other schemas.
const addressSchema = z.object({
street: z.string(),
city: z.string(),
postalCode: z.string(),
});
const userSchema = z.object({
name: z.string(),
address: addressSchema,
});
Arrays
Define arrays using .array().
const stringArraySchema = z.array(z.string());
const numberArraySchema = z.array(z.number());
Enums
Use .enum() to create enums for specific values.
const genderSchema = z.enum(['male', 'female', 'other']);
Union Types
Combine multiple types with .union().
const ageSchema = z.union([z.string(), z.number()]);
Refinements
Add custom validation logic with .refine().
const positiveNumberSchema = z.number().refine(val => val > 0, {
message: 'Must be a positive number',
});
Async Validation
Use .refine() with async functions for asynchronous validation.
const emailSchema = z.string().refine(async val => await isEmailValid(val), {
message: 'Invalid email',
});
Parsing and Error Handling
Use .safeParse() for safer validation with error handling.
const result = userSchema.safeParse(data);
if (!result.success) {
console.error(result.error.format());
}
Type Inference
Zod automatically infers types.
type User = z.infer<typeof userSchema>;
// User type is automatically inferred
Schema Validation with parse()
Use .parse() to validate and throw an error on failure.
const validatedData = userSchema.parse(data);
// Throws error if validation fails
Schema Composition
Schemas can be composed with .merge() and .and(). This is useful for combining schemas.
const userWithAddressSchema = userSchema.merge(addressSchema);
Zod Error Handling
Zod’s error format includes path, message, and issues for detailed error reports.
const result = userSchema.safeParse(data);
if (!result.success) {
console.error(result.error.issues);
}