Zod is a TypeScript-first schema declaration and validation library that helps you create robust type definitions and validate complex data structures with ease. Unlike traditional validation libraries, Zod provides type safety and inference out of the box.
Integrating Zod into your TypeScript project is straightforward and can significantly improve your data validation workflow. This section will guide you through the initial setup and help you understand the basic concepts of getting started with Zod.
Before you begin, ensure you have a TypeScript project set up. Zod is compatible with various package managers, giving you flexibility in your development environment:
Understanding primitive schemas is the foundation of working with Zod. Primitive schemas allow you to define and validate basic data types, ensuring type safety and preventing unexpected data inconsistencies in your application.
Adding constraints to your schemas is a powerful way to ensure data integrity and prevent invalid data from being processed. Here are some examples:
tsx
// String with length constraintsconst usernameSchema = z .string() .min(3, { message: 'Username must be at least 3 characters' }) .max(20, { message: 'Username cannot exceed 20 characters' });// Number with range constraintsconst scoreSchema = z .number() .min(0, { message: 'Score cannot be negative' }) .max(100, { message: 'Score cannot exceed 100' });
Zod provides two primary methods for validation: parse() and safeParse().
Choose parse() when you want to handle validation errors through try/catch blocks, which is useful in scenarios where you want to immediately stop execution and handle the error at a higher level.
Use safeParse() when you need more granular control over validation results and want to handle success/failure cases explicitly without try/catch blocks - this is particularly useful in form validations or API input parsing where you need to examine the specific validation details.
tsx
// Throws an error if validation failstry { const result = nameSchema.parse('Alice'); console.log(result); // 'Alice'} catch (error) { console.error('Validation failed');}
One of Zod's most powerful and useful features is its ability to automatically infer TypeScript types from your schema definitions, eliminating the need to maintain separate type declarations:
tsx
const userSchema = z.object({ name: z.string(), age: z.number().optional(),});// TypeScript knows the exact shape of the objecttype User = z.infer<typeof userSchema>;// Equivalent to: { name: string, age?: number }
note
TypeScript will infer the exact shape of the object from the schema:
Here are some common validation patterns you can use with Zod to ensure data integrity and enforce business rules in your applications. These patterns cover the most frequently used validation scenarios and can be combined to create more complex validation rules:
try { const result = emailSchema.parse('invalid-email');} catch (error) { if (error instanceof z.ZodError) { console.log(error.errors); // Detailed error information }}
By leveraging Zod in your projects, you can create type-safe, robust validation schemas with minimal boilerplate code.
In the next article of this series, we'll dive deeper into more complex validation techniques and advanced schema creation.