Zod - TypeScript Schema Validation
Zod is a TypeScript-first schema validation library with static type inference, designed to validate data at runtime with full TypeScript support.
GitHub
https://github.com/colinhacks/zod
What is Zod?
Zod allows you to:
Key Features
1. TypeScript-First
2. Runtime Validation
3. Composable
Basic Usage
Define a Schema
ypescript
import { z } from 'zod'
// Simple schema
const UserSchema = z.object({
name: z.string(),
age: z.number(),
email: z.string().email(),
})
// Infer TypeScript type
type User = z.infer
// { name: string, age: number, email: string }
Validate Data
ypescript
// Validate and parse
try {
const user = UserSchema.parse({
name: 'John',
age: 30,
email: 'john@example.com',
})
console.log(user)
} catch (error) {
console.error('Validation failed:', error)
}
// Safe parse (doesn't throw)
const result = UserSchema.safeParse({
name: 'John',
age: 'invalid',
})
if (result.success) {
console.log(result.data)
} else {
console.log(result.error)
}
Advanced Validation
ypescript
const UserSchema = z.object({
name: z.string().min(2).max(100),
age: z.number().min(18).max(120),
email: z.string().email(),
website: z.string().url().optional(),
role: z.enum(['admin', 'user', 'guest']),
tags: z.array(z.string()),
metadata: z.record(z.any()),
active: z.boolean().default(true),
createdAt: z.date().default(() => new Date()),
})
Custom Validation
ypescript
const PasswordSchema = z.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[A-Z]/, 'Must contain uppercase letter')
.regex(/[0-9]/, 'Must contain number')
.regex(/[^a-zA-Z0-9]/, 'Must contain special character')
Transform Data
ypescript
const UserSchema = z.object({
email: z.string().email().toLowerCase(),
age: z.string().transform(val => parseInt(val, 10)),
name: z.string().trim(),
})
const result = UserSchema.parse({
email: 'JOHN@EXAMPLE.COM',
age: '30',
name: ' John ',
})
// { email: 'john@example.com', age: 30, name: 'John' }
Real-World Examples
API Response Validation
ypescript
const ApiResponseSchema = z.object({
success: z.boolean(),
data: z.object({
users: z.array(UserSchema),
total: z.number(),
}),
})
// Fetch and validate
async function fetchUsers() {
const response = await fetch('/api/users')
const data = await response.json()
return ApiResponseSchema.parse(data)
}
Form Validation
ypescript
const LoginFormSchema = z.object({
email: z.string().email('Invalid email'),
password: z.string().min(8, 'Password too short'),
})
function handleSubmit(formData: FormData) {
const result = LoginFormSchema.safeParse({
email: formData.get('email'),
password: formData.get('password'),
})
if (!result.success) {
return result.error.errors // Show errors to user
}
// Process form
}
Advantages
Over Manual Validation
| Feature | Manual | Zod |
|---------|--------|-----|
| Type Safety | No | Yes |
| Reusable | No | Yes |
| Error Messages | Manual | Automatic |
| Maintainability | Low | High |
Over Other Libraries
Why Zod?
Summary
Zod is essential for any TypeScript project dealing with external data. Provides runtime validation without sacrificing type safety.
Rating: 猸愨瓙猸愨瓙猸?
Best for: TypeScript projects, API validation, forms
Learning curve: 猸愨瓙
Bundle size: ~3KB (minified)
💬 评论区 (0)
暂无评论,快来抢沙发吧!