mcpField
Z
zod4

zod4

github.com/kastalien-research開発9289 回インストール42 週間前に更新
リポジトリ

zod4 について

Zod 4を使うTypeScript開発者向けに、v3からの移行と標準的なAPIの使い方をまとめたガイドです。破壊的変更、新機能の例、よくある問題への対処を扱います。

主な機能

  1. 01Zod 3から4への移行ガイド
  2. 02破壊的変更と一般的な問題の解説
  3. 03新しいバリデーション機能の例
  4. 04Zod Miniと関数型APIの例
  5. 05移行チェックリストとcodemodの案内

活用シーン

  1. 01プロジェクトをZod 3から4へ更新
  2. 02record、オブジェクト、エラー処理のコードを改修
  3. 03Zod 4の新しい検証機能を採用
  4. 04デフォルト値や型の問題を解決

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/kastalien-research/thoughtbox-dot-claude --skill zod4

インストール後、Claude Code で/zod4を入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

reference/
breaking-changes.md
migration-checklist.md
new-features.md

詳細

Zod 4 エキスパートガイド

Zod 4 は、パフォーマンスの大幅な向上、TypeScript のコンパイル時間の短縮、よりすっきりした API を実現するメジャーリリースです。このスキルでは、v3 からの移行と Zod 4 の慣用的な使い方について説明します。

移行のクイックチェックリスト

詳細に入る前に、影響の大きい以下の破壊的変更に対応してください。

変更点Zod 3Zod 4
レコードスキーマz.record(z.string())z.record(z.string(), z.string())
厳密なオブジェクト.strict()z.strictObject({...})
追加プロパティを許可.passthrough()z.looseObject({...})
エラーのフォーマットerr.format()z.treeifyError(err)
Coerce の入力型stringunknown

Zod 4 をインストールします:

npm install zod@^4.0.0

破壊的変更の詳細については、./reference/breaking-changes.md を参照してください。


主な破壊的変更

1. z.record() には 2 つの引数が必要です
// Zod 3 (BROKEN in v4)
z.record(z.string());

// Zod 4 (REQUIRED)
z.record(z.string(), z.string());
2. 厳密/柔軟なオブジェクトの構文
// Zod 3
z.object({ name: z.string() }).strict();
z.object({ name: z.string() }).passthrough();

// Zod 4
z.strictObject({ name: z.string() });
z.looseObject({ name: z.string() });
3. .default() の動作が変更されました

Zod 4 では、入力が undefined の場合、.default() は処理を中断してデフォルト値を直接返します(解析は行いません)。以前の動作には .prefault() を使用してください:

// Zod 4: default must match OUTPUT type
const schema = z.string()
  .transform(val => val.length)
  .default(0);  // Returns 0 directly, not parsed

// To parse the default (old behavior):
const schema = z.string()
  .transform(val => val.length)
  .prefault("tuna");  // "tuna" is parsed → 4
4. エラー処理の変更
// Zod 3
const formatted = err.format();
const flat = err.flatten();

// Zod 4
const tree = z.treeifyError(err);

// Adding issues
err.issues.push({ /* new issue */ });
5. z.coerce の入力型
const schema = z.coerce.string();
type Input = z.input<typeof schema>;
// Zod 3: string
// Zod 4: unknown

新機能

z.file() - ファイルの検証
const fileSchema = z.file()
  .min(10_000)        // minimum bytes
  .max(1_000_000)     // maximum bytes
  .mime(["image/png", "image/jpeg"]);
z.templateLiteral() - テンプレートリテラル型
const css = z.templateLiteral([z.number(), z.enum(["px", "em", "rem"])]);
// `${number}px` | `${number}em` | `${number}rem`

const email = z.templateLiteral([
  z.string().min(1),
  "@",
  z.string().max(64),
]);
.meta() - スキーマメタデータ
z.string().meta({
  id: "email_address",
  title: "Email address",
  description: "User's email",
  examples: ["[email protected]"]
});
z.globalRegistry - グローバルスキーマレジストリ
z.globalRegistry.add(mySchema, {
  id: "user_schema",
  title: "User",
  description: "User data structure"
});
z.locales - 国際化
import { z } from "zod";
import { en } from "zod/locales/en";

z.config(z.locales.en());  // Configure error messages
z.strictObject() / z.looseObject()
// Rejects unknown keys
z.strictObject({ name: z.string() });

// Allows unknown keys (passthrough)
z.looseObject({ name: z.string() });

新機能の完全なガイドについては、./reference/new-features.md を参照してください。


Zod Mini

Zod Mini(zod/mini)は、ツリーシェイキング可能な関数型 API を備えた、より小さなバンドルを提供します:

import * as z from "zod/mini";

// Functional checks instead of methods
const schema = z.pipe(
  z.string(),
  z.minLength(1),
  z.maxLength(100),
  z.regex(/^[a-z]+$/)
);

// Available functions
z.lt(value);
z.gt(value);
z.positive();
z.negative();
z.minLength(value);
z.maxLength(value);
z.regex(pattern);
z.trim();
z.toLowerCase();
z.toUpperCase();

移行パターン

パターン 1:z.record() の呼び出しを更新する

検索して置換します:

// Find
z.record(valueSchema)

// Replace with
z.record(z.string(), valueSchema)
パターン 2:厳密なオブジェクトを更新する
// Find
z.object({...}).strict()

// Replace with
z.strictObject({...})
パターン 3:エラー処理を更新する
// Find
try {
  schema.parse(data);
} catch (err) {
  if (err instanceof z.ZodError) {
    const formatted = err.format();
  }
}

// Replace with
try {
  schema.parse(data);
} catch (err) {
  if (err instanceof z.ZodError) {
    const tree = z.treeifyError(err);
  }
}
パターン 4:デフォルト値を修正する

変換を伴う .default() を使用している場合は、デフォルト値が出力型に一致するか確認してください:

// If this breaks:
z.string().transform(s => s.length).default("hello")

// Change to:
z.string().transform(s => s.length).prefault("hello")
// OR
z.string().transform(s => s.length).default(5)  // Match output type

移行チェックリストの完全版については、./reference/migration-checklist.md を参照してください。


よくある問題

エラー原因修正方法
Expected 2 arguments, got 1z.record() の引数が 1 つキースキーマを追加します:z.record(z.string(), ...)
Property 'strict' does not exist.strict() が削除されたz.strictObject() を使用します
Property 'format' does not exist.format() が削除されたz.treeifyError(err) を使用します
.default() の型不一致デフォルト値は出力型に一致する必要がある.prefault() を使用するか、デフォルト値の型を修正します

Codemod

コミュニティがメンテナンスする Codemod を利用できます:

npx zod-v3-to-v4

これにより、破壊的変更に伴う修正の多くを自動化できます。


リソース

コメント