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.
Define basic schemas for primitive types.
const stringSchema = z.string(); // Validates strings
const numberSchema = z.number(); // Validates numbers
By default, fields are required.
const userSchema = z.object({
name: z.string(),
age: z.number(),
});
Use .optional()
to define optional fields.
const userSchema = z.object({
name: z.string(),
age: z.number().optional(),
});
Use .default()
to set default values.
const userSchema = z.object({
name: z.string(),
age: z.number().default(18),
});
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,
});
Define arrays using .array()
.
const stringArraySchema = z.array(z.string());
const numberArraySchema = z.array(z.number());
Use .enum()
to create enums for specific values.
const genderSchema = z.enum(['male', 'female', 'other']);
Combine multiple types with .union()
.
const ageSchema = z.union([z.string(), z.number()]);
Add custom validation logic with .refine()
.
const positiveNumberSchema = z.number().refine(val => val > 0, {
message: 'Must be a positive number',
});
Use .refine()
with async functions for asynchronous validation.
const emailSchema = z.string().refine(async val => await isEmailValid(val), {
message: 'Invalid email',
});
Use .safeParse()
for safer validation with error handling.
const result = userSchema.safeParse(data);
if (!result.success) {
console.error(result.error.format());
}
Zod automatically infers types.
type User = z.infer<typeof userSchema>;
// User type is automatically inferred
parse()
Use .parse()
to validate and throw an error on failure.
const validatedData = userSchema.parse(data);
// Throws error if validation fails
Schemas can be composed with .merge()
and .and()
. This is useful for combining schemas.
const userWithAddressSchema = userSchema.merge(addressSchema);
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);
}