Looking for a simple and effective way to validate your data in TypeScript? Discover Zod, the library that will revolutionize how you handle data validation. In just 2 minutes, you'll understand why Zod has become essential!
Why Zod? 🎯
Zod is a validation library that stands out for its:
- Intuitive and concise syntax
- Perfect integration with TypeScript
- Automatic type inference
- Clear and customizable error messages
Quick Installation ⚙️
1npm install zod
2# or
3yarn add zod
Zod Basics in 30 Seconds 🚀
1import { z } from 'zod';
2
3// Simple schema definition
4const userSchema = z.object({
5 name: z.string().min(2, 'Name must contain at least 2 characters'),
6 age: z.number().min(18, 'User must be an adult'),
7 email: z.string().email('Invalid email format'),
8});
9
10// Type inferred automatically!
11type User = z.infer<typeof userSchema>;
12
13// Data validation
14const validateUser = (data: unknown) => {
15 const result = userSchema.safeParse(data);
16 return result.success ? result.data : result.error.issues;
17};
Advanced Features 💪
Conditional Validation
1const formSchema = z
2 .object({
3 type: z.enum(['individual', 'business']),
4 taxId: z.string().optional(),
5 })
6 .refine((data) => !(data.type === 'business' && !data.taxId), {
7 message: 'Tax ID is required for businesses',
8 });
Automatic Transformations
1const dateSchema = z.string().transform((str) => new Date(str));
2const numberSchema = z.string().transform(Number);
Best Practices 🎓
- Prefer
safeParse over parse for more elegant error handling:
1const result = userSchema.safeParse(data);
2if (!result.success) {
3 console.log(result.error.issues);
4 return;
5}
6// Use result.data safely
- Reuse schemas for better maintainability:
1const addressSchema = z.object({
2 street: z.string(),
3 city: z.string(),
4 zipCode: z.string().regex(/^\d{5}$/),
5});
6
7const userSchema = z.object({
8 // ...other fields
9 address: addressSchema,
10});
Common Use Cases 📋
API Validation
1const apiResponseSchema = z.object({
2 status: z.number(),
3 data: z.array(userSchema),
4 metadata: z.record(z.string()),
5});
6
7async function fetchUsers() {
8 const response = await fetch('/api/users');
9 const data = await response.json();
10
11 const result = apiResponseSchema.safeParse(data);
12 if (!result.success) {
13 throw new Error('Invalid API response');
14 }
15
16 return result.data;
17}
Form Validation
1const loginSchema = z.object({
2 email: z.string().email(),
3 password: z.string().min(8),
4});
5
6function handleSubmit(formData: unknown) {
7 const result = loginSchema.safeParse(formData);
8 if (!result.success) {
9 // Display errors
10 return;
11 }
12 // Process validated data
13}
Going Further 🎈
Summary ✨
Zod significantly simplifies data validation in TypeScript while ensuring type safety. Its intuitive syntax and flexibility make it a valuable tool for any TypeScript developer.
Don't hesitate to check the official documentation to deepen your knowledge of Zod!