Zod: Schema Validation
2025年のTypeScript開発に必須の「実行時バリデーション」ライブラリ。
Zod
TypeScript時代のスキーマ検証ライブラリ。実行時の検証と静的な型推論を同時に行う。
詳細解説
Zodを使う最大のメリットは「二重管理の解消」です。スキーマ(検証ルール)を書けば、そこから自動的にTypeScriptの型を生成できます(Type Inference)。
import { z } from "zod";
// 1. Define Schemaconst UserSchema = z.object({ username: z.string().min(3), age: z.number().int().positive(), email: z.string().email().optional(),});
// 2. Infer Type (Automatic!)type User = z.infer<typeof UserSchema>;// { username: string; age: number; email?: string }
// 3. Runtime Validationconst result = UserSchema.safeParse(apiData);if (!result.success) { console.error(result.error);}実践テクニック
APIレスポンスの検証、フォームバリデーション(React Hook Form連携)などで標準的に使われます。
合格ライン
z.infer<> で型を抽出できる
safeParse でエラーハンドリングできる