zod について
Zodは、実行時のデータ検証と静的型の推論を行うTypeScript向けライブラリです。合成可能なスキーマ、変換、エラー処理を必要とする開発者向けです。
主な機能
- 01合成可能な検証スキーマの定義
- 02例外あり・安全なデータ解析
- 03TypeScript型の推論
- 04変換、精査、非同期チェック
- 05JSON Schemaの生成
- 06エラーの整形とローカライズ
活用シーン
- 01APIリクエストとレスポンスの検証
- 02環境変数と設定のチェック
- 03フォーム入力の検証
- 04Zod 3.xスキーマから4.xへの移行
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ secondsky/ claude-skills --skill zodインストール後、Claude Code で/zodを入力して読み込まれたか確認します。
同梱ファイル
SKILL.md と一緒にインストールされる参考資料やスクリプト。
references/advanced-patterns.mdbest-practices.mdcommon-patterns.tsecosystem-integrations.mderror-handling.mdeslint.config.jsmigration-guide.mdpackage.jsonquick-reference.mdtroubleshooting.mdtsconfig.jsontype-inference.md詳細
Zod:TypeScript ファーストのスキーマ検証
概要
Zod は TypeScript ファーストの検証ライブラリです。開発者はデータを実行時に検証するスキーマを定義でき、静的な TypeScript 型も自動的に推論されます。依存関係がなく、コアがコンパクト(gzip 圧縮時に約 5kb、zod/mini は約 1.9kb)な Zod は、包括的なエラー処理を備えた、イミュータブルで合成可能な検証を提供します。
インストール
bun add zod
# or
npm install zod
# or
pnpm add zod
# or
yarn add zod
要件:
tsconfig.jsonで"strict": trueを設定した TypeScript v5.5 以降- Zod 4.x(4.4.x を推奨。
z.codec()には 4.1 以降が必要です)
重要:このスキルでは、Zod 4.x の機能について説明します。以下の API は Zod 4 で必要となり、Zod 3.x では利用できません。
z.codec()- 双方向変換z.iso.date()、z.iso.time()、z.iso.datetime()、z.iso.duration()- ISO 形式のバリデーターz.toJSONSchema()- JSON Schema の生成z.treeifyError()、z.prettifyError()、z.flattenError()- 新しいエラー整形ヘルパー.meta()- 拡張されたメタデータ(Zod 3.x では.describe()のみ)- 統一された
errorパラメーター -message、invalid_type_error、required_error、errorMapを置き換えます .check()- 複数の問題を検証する低レベル API(z.minLength(3)などのチェックファクトリーを合成します)z.file()、z.json()、z.stringbool()、z.xor()、z.templateLiteral()- 新しいスキーマ型z.exactOptional()、.prefault()、.safeExtend()、z.fromJSONSchema()- 新しいユーティリティ
Zod 3.x との互換性や移行方法については、https://zod.dev を参照してください。
インポートパス(すべて zod パッケージに含まれています):
import { z } from "zod"— 標準(4.0 以降は v4)import { z } from "zod/v4"— v3(3.25 以降)と v4 の両方をサポートするライブラリ向けにバージョンを固定しますimport { z } from "zod/mini"— 関数型で、ツリーシェイキング可能な API(約 1.9kb。.check(z.minLength(3))で検証)import * as core from "zod/v4/core"— ライブラリ作成者向けの、$を接頭辞とする低レベルの内部 API
Zod v3 から v4 への移行
v3 から v4 への移行に関する完全なドキュメントを確認するには、references/migration-guide.md を読み込んでください。
クイックサマリー
Zod v4 では、パフォーマンス向上のために破壊的変更が導入されています。
- エラーのカスタマイズ:統一された
errorパラメーターを使用します(message、invalid_type_error、required_errorを置き換えます) - 数値の検証:より厳密になり、
Infinityと安全でない整数を拒否します - 文字列形式:トップレベル関数を推奨します(
z.string().email()ではなくz.email()。メソッド形式も引き続き使用できますが、非推奨です) - オブジェクトのデフォルト値:オプショナルフィールドでも適用されます
- 非推奨 API:
.merge()ではなく.extend()、error.format()ではなくz.treeifyError()を使用します - 関数の検証:
.implement()メソッドを使用します - UUID の検証:RFC 9562/4122 への準拠がより厳密になりました
→ 以下については references/migration-guide.md を読み込んでください: 破壊的変更の全容、移行チェックリスト、段階的な移行戦略、ロールバック手順
コアコンセプト
基本的な使用パターン
import { z } from "zod";
// Define schema
const UserSchema = z.object({
username: z.string(),
age: z.number().int().positive(),
email: z.email(),
});
// Infer TypeScript type
type User = z.infer<typeof UserSchema>;
// Validate data (throws on error)
const user = UserSchema.parse(data);
// Validate data (returns result object)
const result = UserSchema.safeParse(data);
if (result.success) {
console.log(result.data); // Typed!
} else {
console.error(result.error); // ZodError
}
パースメソッド
エラー処理の要件に応じて、適切なパースメソッドを使用します。
.parse(data)- 入力が無効な場合はZodErrorをスローし、成功時には型が厳密に指定されたデータを返します.safeParse(data)-{ success: true, data }または{ success: false, error }を返します(例外は発生しません).parseAsync(data)- 非同期の refinement や transform を含むスキーマ向けです.safeParseAsync(data)- 例外をスローしない非同期版です
ベストプラクティス:try-catch ブロックを避け、判別可能なユニオンを活用するために、.safeParse() を使用してください。
プリミティブ型
文字列
z.string() // Basic string
z.string().min(5) // Minimum length
z.string().max(100) // Maximum length
z.string().length(10) // Exact length
z.email() // Email validation (top-level in v4)
z.url() // URL validation (top-level in v4)
z.uuid() // UUID (RFC 9562; use z.guid() for permissive)
z.uuidv4() // Version-specific UUIDs (also z.uuidv7)
z.httpUrl() // http/https URLs only (rejects ftp:// etc.)
z.e164() // Phone numbers (E.164 format)
z.string().regex(/^\d+$/) // Custom pattern
z.string().startsWith("pre") // Prefix check
z.string().endsWith("suf") // Suffix check
z.string().trim() // Auto-trim whitespace
z.string().toLowerCase() // Auto-lowercase
z.string().toUpperCase() // Auto-uppercase
// ISO formats (Zod 4+)
z.iso.date() // YYYY-MM-DD
z.iso.time() // HH:MM:SS
z.iso.datetime() // ISO 8601 datetime
z.iso.duration() // ISO 8601 duration
// Network formats
z.ipv4() // IPv4 address
z.ipv6() // IPv6 address
z.cidrv4() // IPv4 CIDR notation
z.cidrv6() // IPv6 CIDR notation
// Other formats
z.jwt() // JWT token
z.nanoid() // Nanoid
z.cuid() // CUID
z.cuid2() // CUID2
z.ulid() // ULID
z.base64() // Base64 encoded
z.hex() // Hexadecimal
z.hash("sha256") // Hash of algorithm-specific length
z.guid() // Permissive UUID/GUID (non-RFC)
z.hostname() // Hostname
z.mac() // MAC address
z.uuid({ version: "v4" }) // UUID with version constraint
z.email({ pattern: z.regexes.email }) // Email with explicit pattern
数値
z.number() // Basic number
z.number().int() // Integer only
z.number().positive() // > 0
z.number().nonnegative() // >= 0
z.number().negative() // < 0
z.number().nonpositive() // <= 0
z.number().min(0) // Minimum value
z.number().max(100) // Maximum value
z.number().gt(0) // Greater than
z.number().gte(0) // Greater than or equal
z.number().lt(100) // Less than
z.number().lte(100) // Less than or equal
z.number().multipleOf(5) // Must be multiple of 5
z.int() // Shorthand for z.number().int()
z.int32() // 32-bit integer (also z.uint32, z.int64, z.uint64)
z.float32() // 32-bit float (also z.float64)
z.nan() // NaN value
強制変換(型変換)
z.coerce.string() // Convert to string
z.coerce.number() // Convert to number
z.coerce.boolean() // Convert to boolean
z.coerce.bigint() // Convert to bigint
z.coerce.date() // Convert to Date
// Example: Parse query parameters
const QuerySchema = z.object({
page: z.coerce.number().int().positive(),
limit: z.coerce.number().int().max(100).default(10),
});
// "?page=5&limit=20" -> { page: 5, limit: 20 }
その他のプリミティブ型
z.boolean() // Boolean
z.date() // Date object
z.date().min(new Date("2020-01-01"))
z.date().max(new Date("2030-12-31"))
z.bigint() // BigInt
z.symbol() // Symbol
z.null() // Null
z.undefined() // Undefined
z.void() // Void (undefined)
// File validation (v4) — sizes are bytes
z.file().min(1).max(5 * 1024 * 1024).mime(["image/png"])
// JSON-representable values (v4) — validates the VALUE is JSON-serializable
// (recursive union of string | number | boolean | null | array | record)
z.json()
// Env-style boolean coercion: "true"/"yes"/"1" → true (v4)
z.stringbool({ truthy: ["true", "yes", "1"], falsy: ["false", "no", "0"] })
複合型
オブジェクト
const PersonSchema = z.object({
name: z.string(),
age: z.number(),
address: z.object({
street: z.string(),
city: z.string(),
country: z.string(),
}),
});
type Person = z.infer<typeof PersonSchema>;
// Object methods
PersonSchema.shape // Access shape
PersonSchema.keyof() // Get union of keys
PersonSchema.extend({ role: z.string() }) // Add fields
PersonSchema.safeExtend({ role: z.string() }) // Type-safe extend (inherits refinements)
PersonSchema.pick({ name: true }) // Pick specific fields
PersonSchema.omit({ age: true }) // Omit fields
PersonSchema.partial() // Make all fields optional
PersonSchema.partial({ age: true }) // Make specific fields optional
PersonSchema.required() // Make all fields required
// NOTE: .deepPartial() was REMOVED in v4 — build recursive partials manually
// (top-level z.deepPartial() landed post-4.4.3 and is not yet stable)
// Strict vs loose objects
z.strictObject({ ... }) // No extra keys allowed (throws)
z.object({ ... }) // Strips extra keys (default)
z.looseObject({ ... }) // Allows extra keys
z.object({ ... }).catchall(z.number()) // Validate (and keep) unknown keys
配列
z.array(z.string()) // String array
z.array(z.number()).min(1) // At least 1 element
z.array(z.number()).max(10) // At most 10 elements
z.array(z.number()).length(5) // Exactly 5 elements
z.array(z.number()).nonempty() // At least 1 element
// Nested arrays
z.array(z.array(z.number())) // number[][]
タプル
z.tuple([z.string(), z.number()]) // [string, number]
z.tuple([z.string(), z.number()]).rest(z.boolean()) // [string, number, ...boolean[]]
列挙型とリテラル
// Enum
const RoleEnum = z.enum(["admin", "user", "guest"]);
type Role = z.infer<typeof RoleEnum>; // "admin" | "user" | "guest"
// Literal values
z.literal("exact_value")
z.literal(42)
z.literal(true)
// Native TypeScript enum
enum Fruits {
Apple,
Banana,
}
z.nativeEnum(Fruits)
// Enum methods
RoleEnum.enum.admin // "admin"
RoleEnum.exclude(["guest"]) // Exclude values
RoleEnum.extract(["admin", "user"]) // Include only
ユニオン
// Basic union
z.union([z.string(), z.number()])
// Discriminated union (better performance & type inference)
const ResponseSchema = z.discriminatedUnion("status", [
z.object({ status: z.literal("success"), data: z.any() }),
z.object({ status: z.literal("error"), message: z.string() }),
]);
type Response = z.infer<typeof ResponseSchema>;
// { status: "success", data: any } | { status: "error", message: string }
// Exclusive union (v4): must match exactly ONE branch
z.xor([z.object({ a: z.string() }), z.object({ b: z.number() })])
インターセクション
const BaseSchema = z.object({ id: z.string() });
const ExtendedSchema = z.object({ name: z.string() });
const Combined = z.intersection(BaseSchema, ExtendedSchema);
// Equivalent to: z.object({ id: z.string(), name: z.string() })
レコードとマップ
// Record: object with typed keys and values (BOTH args required in v4)
z.record(z.string(), z.number()) // { [key: string]: number }
z.record(z.enum(["a", "b"]), z.string()) // Exhaustive: both keys REQUIRED
// Partial record (enum keys optional)
z.partialRecord(z.enum(["a", "b"]), z.string())
// Map
z.map(z.string(), z.number()) // Map<string, number>
z.set(z.string()) // Set<string>
高度なパターン
高度な検証と変換のパターンについて詳しくは、references/advanced-patterns.md を読み込んでください。
クイックリファレンス
絞り込み(カスタム検証):
z.string().refine((val) => val.length >= 8, "Too short");
z.object({ password, confirmPassword }).superRefine((data, ctx) => { /* ... */ });
変換(データの変更):
z.string().transform((val) => val.trim());
z.string().pipe(z.coerce.number());
z.preprocess((v) => (typeof v === "string" ? v.trim() : v), z.string()); // Transform BEFORE parsing
z.custom<string>((v) => typeof v === "string", { error: "Not a string" }); // Fully custom schema
複数の問題の検証(.check()、v4):
z.string().check(z.minLength(3), z.startsWith("a")); // Compose check factories
z.string().check((payload) => {
if (payload.value === "forbidden") {
payload.issues.push({ code: "custom", message: "Not allowed", input: payload.value });
}
});
テンプレートリテラル(v4):
const UserRole = z.templateLiteral(["role-", z.string()]); // "role-admin", "role-editor", ...
コーデック(双方向変換 — v4.1 で新登場):
const DateCodec = z.codec(
z.iso.datetime(),
z.date(),
{
decode: (str) => new Date(str),
encode: (date) => date.toISOString(),
}
);
再帰型:
const CategorySchema: z.ZodType<Category> = z.lazy(() =>
z.object({ name: z.string(), subcategories: z.array(CategorySchema) })
);
オプション/Nullable:
z.string().optional() // string | undefined
z.string().nullable() // string | null
z.string().default("default") // Provides default if undefined
読み取り専用とブランド:
z.object({ ... }).readonly() // Readonly properties
z.string().brand<"UserId">() // Nominal typing
→ 次の項目については、references/advanced-patterns.md を読み込んでください: 完全な絞り込みパターン、非同期検証、コーデックの例、合成可能なスキーマ、条件付き検証、パフォーマンスの最適化
エラー処理
エラーの書式設定とカスタマイズに関する完全なガイドについては、references/error-handling.md を読み込んでください。
クイックリファレンス
エラー書式設定メソッド:
// For forms
const { fieldErrors } = z.flattenError(error);
// For nested data
const tree = z.treeifyError(error);
const nameError = tree.properties?.user?.properties?.name?.errors?.[0];
// For debugging
console.log(z.prettifyError(error));
カスタムエラーメッセージ(3 つのレベル):
// 1. Schema-level (highest priority)
z.string({ error: "Custom message" });
z.string().min(5, "Too short");
// 2. Per-parse level
schema.parse(data, { error: (issue) => "..." });
// 3. Global level
z.config({ customError: (issue) => "..." });
ローカライズ(40 以上の言語):
z.config(z.locales.es()); // Spanish
z.config(z.locales.fr()); // French
→ 次の項目については、references/error-handling.md を読み込んでください: エラー書式設定の完全な例、カスタムエラーパターン、ローカライズの設定、エラーコードのリファレンス
型推論
型推論とメタデータに関する完全なドキュメントについては、references/type-inference.md を読み込んでください。
クイックリファレンス
基本的な型推論:
const UserSchema = z.object({ name: z.string() });
type User = z.infer<typeof UserSchema>; // { name: string }
入力と出力(変換の場合):
const TransformSchema = z.string().transform((s) => s.length);
type Input = z.input<typeof TransformSchema>; // string
type Output = z.output<typeof TransformSchema>; // number
JSON Schema への変換:
const jsonSchema = z.toJSONSchema(UserSchema, {
target: "openapi-3.0",
// .meta() data from the global registry is included by default
});
メタデータ:
// Add metadata
const EmailSchema = z.email().meta({
title: "Email Address",
description: "User's email address",
});
// Create custom registry
const formRegistry = z.registry<FormFieldMeta>();
→ 次の項目については、references/type-inference.md を読み込んでください: 型推論の完全なパターン、JSON Schema のオプション、メタデータシステム、カスタムレジストリ、ブランド型
関数
v4 のファクトリーシグネチャで関数の入力と出力を検証します:
const AddFunction = z.function({
input: [z.number(), z.number()], // Arguments
output: z.number(), // Return type
});
// Implement typed function
const add = AddFunction.implement((a, b) => {
return a + b; // Type-checked!
});
// Async functions
const FetchFunction = z.function({
input: [z.string()],
output: z.object({ data: z.any() }),
});
const fetchJson = FetchFunction.implementAsync(async (url) => {
const response = await fetch(url);
return response.json();
});
注:v3 のチェーン形式(z.function().args(...).returns(...))は v4 で削除されました。
一般的なパターン
環境変数
const EnvSchema = z.object({
NODE_ENV: z.enum(["development", "production", "test"]),
DATABASE_URL: z.url(),
PORT: z.coerce.number().int().positive().default(3000),
API_KEY: z.string().min(32),
});
// Validate on startup
const env = EnvSchema.parse(process.env);
// Now use typed env
console.log(env.PORT); // number
API リクエストの検証
const CreateUserRequest = z.object({
username: z.string().min(3).max(20),
email: z.email(),
password: z.string().min(8),
age: z.number().int().positive().optional(),
});
// Express example
app.post("/users", async (req, res) => {
const result = CreateUserRequest.safeParse(req.body);
if (!result.success) {
return res.status(400).json({
errors: z.flattenError(result.error).fieldErrors,
});
}
const user = await createUser(result.data);
res.json(user);
});
フォームの検証
const FormSchema = z.object({
firstName: z.string().min(1, "First name required"),
lastName: z.string().min(1, "Last name required"),
email: z.email({ error: "Invalid email" }),
age: z.coerce.number().int().min(18, "Must be 18+"),
agreeToTerms: z.literal(true, {
error: () => "Must accept terms",
}),
});
type FormData = z.infer<typeof FormSchema>;
部分更新
const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.email(),
});
// For PATCH requests: make everything optional except id
const UpdateUserSchema = UserSchema.partial().required({ id: true });
type UpdateUser = z.infer<typeof UpdateUserSchema>;
// { id: string; name?: string; email?: string }
合成可能なスキーマ
// Base schemas
const TimestampSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
});
const AuthorSchema = z.object({
authorId: z.string(),
authorName: z.string(),
});
// Compose into larger schemas (.merge() is deprecated — use .extend with .shape)
const PostSchema = z.object({
id: z.string(),
title: z.string(),
content: z.string(),
}).extend(TimestampSchema.shape).extend(AuthorSchema.shape);
エコシステムとの統合
フレームワークやツールとの統合に関する完全なガイドについては、references/ecosystem-integrations.md を読み込んでください。
クイックリファレンス
ESLint プラグイン:
eslint-plugin-zod-x- ベストプラクティスを適用しますeslint-plugin-import-zod- インポート形式を適用します
フレームワークとの統合:
- tRPC - エンドツーエンドの型安全な API
- React Hook Form - フォームの検証(
react-hook-form-zodスキルを参照) - Prisma - データベースモデルから Zod を生成
- NestJS - DTO と検証パイプ
コード生成:
- orval - OpenAPI → Zod
- Hey API - OpenAPI から TypeScript + Zod へ
- kubb - コード生成機能を備えた API ツールキット
→ 次の項目については、references/ecosystem-integrations.md を読み込んでください: セットアップ手順、統合の例、Hono ミドルウェア、Drizzle ORM のパターン
トラブルシューティング
トラブルシューティングの完全なガイド、パフォーマンスのヒント、ベストプラクティスについては、references/troubleshooting.md を読み込んでください。
クイックリファレンス
よくある問題:
- TypeScript の strict モードが必要 →
tsconfig.jsonで有効にします - バンドルサイズが大きい → コード分割には
z.lazy()を使用します - 非同期の絞り込みが遅い → キャッシュまたはデバウンスを使用します
- 循環依存 →
z.lazy()を使用します - ユニオンが遅い →
z.discriminatedUnion()を使用します - transform と refine の混同 → 検証には
.refine()、変更には.transform()を使用します
パフォーマンスのヒント:
.discriminatedUnion()を使用します(.union()より 5~10 倍高速です)- スキーマインスタンスをキャッシュします
.safeParse()を使用します(try-catch のオーバーヘッドを回避します)- 大きなスキーマを遅延読み込みします
ベストプラクティス:
- モジュールレベルでスキーマを定義します
- 型推論(
z.infer)を使用します - カスタムエラーメッセージを追加します
- システム境界で検証します
- 小さなスキーマを合成します
.meta()でドキュメントを記述します
→ 次の項目については、references/troubleshooting.md を読み込んでください: 詳細な解決策、パフォーマンスの最適化、ベストプラクティス、テストパターン
クイックリファレンス
// Primitives
z.string(), z.number(), z.boolean(), z.date(), z.bigint()
// Collections
z.array(), z.tuple(), z.object(), z.record(), z.map(), z.set()
// Special types
z.enum(), z.union(), z.discriminatedUnion(), z.intersection()
z.literal(), z.any(), z.unknown(), z.never()
// Modifiers
.optional(), .nullable(), .nullish(), .default(), .prefault()
.catch(), .readonly(), .brand(), .exactOptional()
// Validation
.min(), .max(), .length(), .regex()
.refine(), .superRefine(), .check(z.minLength(3))
// Top-level formats (v4)
z.email(), z.uuid(), z.url(), z.iso.datetime(), z.file(), z.json()
// Transformation
.transform(), .pipe(), .codec(), z.preprocess(), z.custom()
// Composition helpers
z.strictObject(), z.looseObject(), z.xor(), z.templateLiteral()
// Parsing
.parse(), .safeParse(), .parseAsync(), .safeParseAsync()
// Type inference
z.infer<typeof Schema>, z.input<typeof Schema>, z.output<typeof Schema>
// Error handling
z.flattenError(), z.treeifyError(), z.prettifyError()
// JSON Schema
z.toJSONSchema(schema, options)
// Metadata
.meta(), .describe()
// Object methods
.extend(), .safeExtend(), .pick(), .omit(), .partial(), .required()
.catchall(), .keyof() // .merge() is deprecated — use .extend(other.shape)
リファレンスを読み込むタイミング
次の場合は references/migration-guide.md を読み込んでください:
- Zod v3 から v4 にアップグレードする
- 破壊的変更について確認する
- 移行チェックリストやロールバック戦略が必要
- 非推奨 API(
.merge()、error.format()など)に関連するエラーが発生した Infinityや安全でない整数に関する数値検証の問題がある
次の場合は references/error-handling.md を読み込んでください:
- フォームや UI 向けにエラーを整形する必要がある
- カスタムエラーメッセージを実装する
z.flattenError()、z.treeifyError()、z.prettifyError()について確認する- エラーメッセージのローカライズを設定する
- エラーコードのリファレンスやパターンの例が必要
次の場合は references/advanced-patterns.md を読み込んでください:
- カスタムリファインメントや非同期バリデーションを実装する
- 双方向変換(コーデック)が必要
- 再帰型または自己参照データを扱う
.refine()、.transform()、.codec()について確認する- パフォーマンス最適化のパターンが必要
- 条件付きバリデーションを実装する
次の場合は references/type-inference.md を読み込んでください:
- TypeScript の型推論について確認する
- OpenAPI または AI 向けに JSON Schema を生成する
- フォームやドキュメント向けのメタデータシステムを実装する
- 型安全なメタデータ用のカスタムレジストリが必要
z.infer、z.input、z.outputについて確認する- ID の安全性のためにブランド型を使用する
次の場合は references/ecosystem-integrations.md を読み込んでください:
- tRPC、React Hook Form、Prisma、NestJS と統合する
- ベストプラクティスに沿った ESLint プラグインを設定する
- OpenAPI から Zod スキーマを生成する(orval、Hey API、kubb)
- Hono ミドルウェアや Drizzle ORM について確認する
- フレームワーク固有の統合例が必要
次の場合は references/troubleshooting.md を読み込んでください:
- TypeScript の strict モードでエラーが発生した
- バンドルサイズが気になる、または遅延読み込みが必要
- 大規模なユニオン型や非同期リファインメントでパフォーマンスの問題がある
- 循環依存について確認する
- ベストプラクティスやテストのパターンが必要
.refine()と.transform()の違いがわからない
次の場合は references/best-practices.md を読み込んでください:
- 本番環境向けの Zod コードを記述する、または Zod の使用状況をレビューする
- 厳格なオブジェクトと緩いオブジェクト、optional と nullable、
anyとunknownのどれを使うか決める - ホットパスを最適化する(スキーマのキャッシュ、動的なスキーマ作成の回避、大きな配列)
- どこで検証するか迷っている(境界、
JSON.parse、二重検証) - 「使用すべきでない場合」の説明を含む誤った例と正しい例が必要
追加リソース
- 公式ドキュメント: https://zod.dev
- GitHub: https://github.com/colinhacks/zod
- TypeScript Playground: https://zod-playground.vercel.app
- Zod Mini: https://zod.dev/packages/mini
- ESLint プラグイン(ベストプラクティス): https://github.com/JoshuaKGoldberg/eslint-plugin-zod-x
- tRPC 連携: https://trpc.io
- エコシステム: https://zod.dev/ecosystem
本番環境向け情報:
- パッケージバージョン: 4.4.x(すべての API は [email protected] に対して検証済み)
- 依存関係なし
- バンドルサイズ: コアは約 5kb / zod/mini は約 1.9kb(gzip 圧縮時)
- TypeScript 5.5 以降が必要です
- strict モードが必要です
- 最終検証日: 2026-08-20
- スキルバージョン: 2.1.0(忠実性監査+ベストプラクティスのルール)
2.1.0 の新機能:
- 🔍 忠実性監査: ドキュメントに記載されているすべての API を [email protected] に対して検証済み(型チェック+実行時テスト)
- 📜 新しい
references/best-practices.mdルールブック(影響度の評価付きの「誤り/正しい方法/使用しないケース」形式) - ➕ 新たに追加された対象:
zod/mini、.check()、catchall、z.preprocess、z.custom、z.templateLiteral、z.file/z.json/z.stringbool/z.xor、z.exactOptional、.safeExtend、z.fromJSONSchema、拡張された形式バリデーター - 🐛 修正: インストールコマンド、
z.string().uuid()→z.uuid()、v3 の.merge()/z.function()チェーン、.deepPartial()(v4 で削除)、単一引数のz.record、toJSONSchemaのmetadataオプション
2.0.0 の新機能:
- ✨ 破壊的変更を含む、v3 から v4 への包括的な移行ガイド
- ✨ 3 段階のシステムによるエラーのカスタマイズ機能の強化
- ✨ レジストリーシステムによるメタデータ API の拡充
- ✨ 実践的な例によるエラー整形機能の改善
- ✨ 40 以上のロケールに対応した組み込みのローカライズサポート
- ✨ 実際のユースケースに沿った詳細な Codec ドキュメント
- ✨ パフォーマンスの改善とアーキテクチャの変更についての解説