Zod 4 では、エラーの形を変える関数が z.treeifyError、z.prettifyError、z.flattenError に変わり、Zod 3 の .format() と .flatten() は非推奨になりました。メッセージを変える書き方も error に1本化され、required_error や errorMap はなくなっています。この記事では、入れ子のオブジェクトと配列を持つスキーマに同じ不正な入力を渡して、issues と3つの関数の出力を並べて比べました。日本語のメッセージにする方法と、Zod 3 の書き方を Zod 4 で動かしたときに何が起きるか(そのまま動くもの、黙って無視されるもの、型検査でだけ分かるもの)も確かめています。
結論
| やりたいこと | 使うもの | 今回の確認で分かったこと |
|---|---|---|
| エラーの中身をそのまま見る | result.error.issues | 1つの問題が1つの issue。path に場所(["items",1,"sku"] など)が入る |
| 入れ子のフォームで、項目ごとにエラーを出す | z.treeifyError() | スキーマと同じ形の木になる。?. でたどる |
| ログや画面に読みやすく出す | z.prettifyError() | 1件ずつ「✖ メッセージ」と「→ at 場所」の行が並ぶ文字列。パスの短い順に並ぶ |
| 1階層のフォームでエラーを出す | z.flattenError() | 入れ子のエラーは、いちばん上のキーにまとめられる(どの項目のエラーか分からなくなる) |
| メッセージを日本語にする | z.config(z.locales.ja()) | 標準のメッセージが日本語になる |
| メッセージを自分で決める | error に文字列か関数を渡す | 関数なら iss.input === undefined で「未入力」と「型違い」を分けられる |
- Zod 3 の
message、.format()、.flatten()は、Zod 4 でも動きました(非推奨)。 - Zod 3 の
required_error、invalid_type_error、errorMapは、実行してもエラーにならず、黙って無視されて標準のメッセージになりました。.formErrors、.errorsはundefinedでした。 - 削除された書き方は、
tscの型検査ではエラーになりました。非推奨のほうは、型検査でもエラーになりません。Zod 3 から移るときは、実行だけでなく型検査も通してください。 safeParseが返すエラーも、parseが投げるエラーも、Zod 4.6.7 ではErrorを継承していて、messageには issues の JSON が入っていました。
動作確認した環境
- Zod 4.6.7、TypeScript 7.0.2
- Node.js 26.13.1(Dockerイメージ
node:26.13.1-slim。digestで固定)。.tsのファイルを、Node.js の型の除去(type stripping)で直接実行した - Docker 29.9.3(Windows 11 の Docker Desktop、Linuxコンテナ、x86_64)
- 実行したシェル: Git Bash(本文の手順をすべて)、PowerShell 7.6.10(一部)。Mac では実行していない
- 確認日: 2026-11-25
Node.js も TypeScript もパソコンに入れずに試せるように、コマンドはすべて Docker のコンテナで実行します。Node.js 26 がパソコンに入っていれば、zrun を外して同じコマンドを実行しても動くはずですが、試していません。
手順
1. 準備
作業用のフォルダを作り、イメージの名前と、コンテナでコマンドを実行する関数 zrun を決めます。Mac のターミナルと Windows の Git Bash で同じ書き方です。Git Bash では、-w /app が Windows のパスに書き換えられないように、最初に MSYS_NO_PATHCONV=1 を設定します(Mac では要りません)。PowerShell の書き方は、後の「PowerShell の場合」にあります。
mkdir zod-errors
cd zod-errors
export MSYS_NO_PATHCONV=1 # Git Bash だけ
IMG=node:26.13.1-slim@sha256:abe7e5a82b61a8ef67b315b85497c9e65173387ccf2f4a029248184b8e020be5
zrun() { docker run --rm -v "$PWD":/app -w /app "$IMG" "$@"; }
zrun node -v
v26.13.1
package.json を作ります。"type": "module" で、import の書き方を使えるようにします。
{
"name": "zod-errors",
"private": true,
"type": "module"
}
Zod と TypeScript を入れます。TypeScript は、最後の型検査でだけ使います。
zrun npm install zod@4.6.7 typescript@7.0.2
added 3 packages in 14s
TypeScript 7 は Go で書き直された版で、OS ごとの実行ファイルが別のパッケージで入ります。コンテナで入れた node_modules には Linux 用のものしか入らないので、パソコンの Node.js からそのまま使わないでください(使うなら、パソコンで入れ直します)。
2. スキーマと不正な入力
注文を表すスキーマです。customer は入れ子のオブジェクト、tags は文字列の配列、items はオブジェクトの配列です。badInput には、名前が空、メールアドレスの形が違う、tags に数値、2つ目の商品の sku が数値で数量が0、という5つの問題を入れました。このあとの例は、すべてこの2つを使います。
schema.ts
import * as z from "zod";
export const Order = z.object({
customer: z.object({
name: z.string().min(1),
email: z.email(),
}),
tags: z.array(z.string()).max(3),
items: z
.array(
z.object({
sku: z.string(),
quantity: z.int().positive(),
}),
)
.min(1),
});
export const badInput = {
customer: { name: "", email: "not-an-email" },
tags: ["typescript", 42],
items: [
{ sku: "A-1", quantity: 2 },
{ sku: 123, quantity: 0 },
],
};
3. issues を見る
safeParse は例外を投げず、失敗したら result.error を返します。result.error.issues が、エラーの元のデータです。
1-issues.ts
import { Order, badInput } from "./schema.ts";
const result = Order.safeParse(badInput);
if (!result.success) {
console.log(result.error.issues.length, "件");
for (const issue of result.error.issues) {
console.log(issue.code, JSON.stringify(issue.path), issue.message);
}
console.log(result.error.issues[3]);
}
zrun node 1-issues.ts
5 件
too_small ["customer","name"] Too small: expected string to have >=1 characters
invalid_format ["customer","email"] Invalid email address
invalid_type ["tags",1] Invalid input: expected string, received number
invalid_type ["items",1,"sku"] Invalid input: expected string, received number
too_small ["items",1,"quantity"] Too small: expected number to be >0
{
expected: 'string',
code: 'invalid_type',
path: [ 'items', 1, 'sku' ],
message: 'Invalid input: expected string, received number'
}
5つの問題が、5つの issue になりました。path は、オブジェクトのキーと配列の番号の並びです。code は問題の種類(invalid_type、too_small、invalid_format など)で、メッセージを自分で作るときの分岐に使えます。issue には入力の値は入りません(公式ドキュメントによると、機密の値がログに出ないようにするため。入れたいときは reportInput: true)。
4. safeParse と parse のエラー
parse は、失敗すると ZodError を投げます。safeParse のエラーと、Error を継承しているかを比べます。
2-error-class.ts
import * as z from "zod";
import { Order, badInput } from "./schema.ts";
const result = Order.safeParse(badInput);
if (!result.success) {
console.log("safeParse:", result.error instanceof z.ZodError, result.error instanceof Error);
console.log("message:", JSON.stringify(result.error.message.slice(0, 30)));
}
try {
Order.parse(badInput);
} catch (e) {
console.log("parse:", e instanceof z.ZodError, e instanceof Error);
}
zrun node 2-error-class.ts
safeParse: true true
message: "[\n {\n \"origin\": \"string\",\n"
parse: true true
どちらも ZodError で、Error も継承していました。インストールされた zod/v4/classic/parse.js では、parse も safeParse も、Error を継承するクラス ZodRealError でエラーを作っています。message には issues の JSON が入るので、ログに出すと長くなります。人が読む形で出すなら、次の z.prettifyError を使います。失敗の判定は、safeParse なら result.success、parse なら instanceof z.ZodError で行います。
5. treeifyError、prettifyError、flattenError
同じエラーを3つの関数に渡します。
3-format.ts
import * as z from "zod";
import { Order, badInput } from "./schema.ts";
const result = Order.safeParse(badInput);
if (!result.success) {
const tree = z.treeifyError(result.error);
console.log("--- treeifyError");
console.dir(tree, { depth: null });
console.log("--- items[1].quantity のエラー");
console.log(tree.properties?.items?.items?.[1]?.properties?.quantity?.errors);
console.log("--- prettifyError");
console.log(z.prettifyError(result.error));
console.log("--- flattenError");
console.dir(z.flattenError(result.error), { depth: null });
}
zrun node 3-format.ts
--- treeifyError
{
errors: [],
properties: {
customer: {
errors: [],
properties: {
name: {
errors: [ 'Too small: expected string to have >=1 characters' ]
},
email: { errors: [ 'Invalid email address' ] }
}
},
tags: {
errors: [],
items: [
<1 empty item>,
{
errors: [ 'Invalid input: expected string, received number' ]
}
]
},
items: {
errors: [],
items: [
<1 empty item>,
{
errors: [],
properties: {
sku: {
errors: [ 'Invalid input: expected string, received number' ]
},
quantity: { errors: [ 'Too small: expected number to be >0' ] }
}
}
]
}
}
}
--- items[1].quantity のエラー
[ 'Too small: expected number to be >0' ]
--- prettifyError
✖ Too small: expected string to have >=1 characters
→ at customer.name
✖ Invalid email address
→ at customer.email
✖ Invalid input: expected string, received number
→ at tags[1]
✖ Invalid input: expected string, received number
→ at items[1].sku
✖ Too small: expected number to be >0
→ at items[1].quantity
--- flattenError
{
formErrors: [],
fieldErrors: {
customer: [
'Too small: expected string to have >=1 characters',
'Invalid email address'
],
tags: [ 'Invalid input: expected string, received number' ],
items: [
'Invalid input: expected string, received number',
'Too small: expected number to be >0'
]
}
}
z.treeifyError: スキーマと同じ形の木になります。オブジェクトはproperties、配列はitemsでたどり、それぞれの場所のメッセージがerrorsに入ります。エラーのない配列の要素は空(<1 empty item>)なので、?.でたどります。z.prettifyError: 人が読むための文字列です。今回は issues と同じ順番でしたが、実装ではパスの短い順に並べ替えています(インストールされたzod/v4/core/errors.jsのprettifyError)。オブジェクト全体のエラー(パスが空)があれば、先頭に出ます。z.flattenError: いちばん上のキーごとに、メッセージの配列になります。customer.nameとcustomer.emailのエラーはcustomerにまとめられ、どちらの項目のエラーかは分からなくなりました。公式ドキュメントも、1階層のスキーマ向けとしています。
6. 日本語のメッセージ
Zod には、メッセージの翻訳(ロケール)が入っています。z.config(z.locales.ja()) で日本語になります。
4-ja.ts
import * as z from "zod";
import { Order, badInput } from "./schema.ts";
z.config(z.locales.ja());
const result = Order.safeParse(badInput);
if (!result.success) {
console.log(z.prettifyError(result.error));
}
zrun node 4-ja.ts
✖ 小さすぎる値: stringは1文字以上である必要があります
→ at customer.name
✖ 無効なメールアドレス
→ at customer.email
✖ 無効な入力: stringが期待されましたが、数値が入力されました
→ at tags[1]
✖ 無効な入力: stringが期待されましたが、数値が入力されました
→ at items[1].sku
✖ 小さすぎる値: numberは0より大きい必要があります
→ at items[1].quantity
型の名前(string、array など)は英語のまま混ざります。利用者にそのまま見せるなら、次の error で項目ごとに決めるほうが自然です。z.config はアプリ全体の設定なので、最初に1回だけ実行します。
7. error でメッセージを変える
Zod 4 では、メッセージを変える書き方が error に1本化されました。文字列を渡すか、issue を受け取ってメッセージを返す関数を渡します。関数では、iss.input === undefined で「値がない」と「型が違う」を分けられます(Zod 3 の required_error と invalid_type_error の代わり)。
5-custom.ts
import * as z from "zod";
const Name = z
.string({
error: (iss) =>
iss.input === undefined ? "名前は必須です" : "名前は文字列で入力してください",
})
.min(1, { error: "名前を入力してください" });
for (const value of [undefined, 123, ""]) {
const r = Name.safeParse(value);
console.log(JSON.stringify(value), "=>", r.success ? "OK" : r.error.issues.map((i) => `${i.code}: ${i.message}`));
}
zrun node 5-custom.ts
undefined => [ 'invalid_type: 名前は必須です' ]
123 => [ 'invalid_type: 名前は文字列で入力してください' ]
"" => [ 'too_small: 名前を入力してください' ]
空文字("")のときは、スキーマの error の関数ではなく、min(1, ...) につけたメッセージになりました。公式ドキュメントによると、メッセージの優先順位は高い順に、チェック(min など)につけた error、スキーマにつけた error、parse に渡した error、z.config({ customError })、ロケールです。スキーマにつけた error は、そのスキーマのチェックの issue にも使われ、チェックに error がないときの代わりになります。関数が undefined を返すと、次の順位に任せます。今回確かめたのは、チェックがスキーマより優先されることだけです。
8. Zod 3 の書き方を Zod 4 で動かす
Zod 3 のメッセージの書き方とエラーのメソッドを、Zod 4 で実行します。Node.js の型の除去は型を調べないので、型が合わないコードもそのまま動きます。
6-zod3.ts
import * as z from "zod";
// 非推奨: message
const A = z.string().min(5, { message: "5文字以上にしてください" });
console.log("message:", A.safeParse("abc").error?.issues[0].message);
// 削除: required_error、invalid_type_error
const B = z.string({ required_error: "必須です", invalid_type_error: "文字列にしてください" });
console.log("required_error:", B.safeParse(undefined).error?.issues[0].message);
console.log("invalid_type_error:", B.safeParse(1).error?.issues[0].message);
// 削除: errorMap
const C = z.string({ errorMap: () => ({ message: "errorMap のメッセージ" }) });
console.log("errorMap:", C.safeParse(1).error?.issues[0].message);
const err = z.object({ a: z.string() }).safeParse({ a: 1 }).error!;
// 非推奨: format()、flatten()
console.log("format():", JSON.stringify(err.format()));
console.log("flatten():", JSON.stringify(err.flatten()));
// 削除: formErrors、errors
console.log("formErrors:", err.formErrors, "errors:", err.errors);
zrun node 6-zod3.ts
message: 5文字以上にしてください
required_error: Invalid input: expected string, received undefined
invalid_type_error: Invalid input: expected string, received number
errorMap: Invalid input: expected string, received number
format(): {"_errors":[],"a":{"_errors":["Invalid input: expected string, received number"]}}
flatten(): {"formErrors":[],"fieldErrors":{"a":["Invalid input: expected string, received number"]}}
formErrors: undefined errors: undefined
| Zod 3 の書き方 | Zod 4 での扱い(移行ガイド) | 実行の結果 | Zod 4 の書き方 |
|---|---|---|---|
{ message: "..." } | 非推奨 | 動いた | { error: "..." } |
required_error、invalid_type_error | 削除 | 無視されて標準のメッセージ | error に関数を渡し、iss.input === undefined で分ける |
errorMap | 削除(error に名前が変わった) | 無視されて標準のメッセージ | error に関数を渡す |
.format()、.flatten() | 非推奨 | 動いた | z.treeifyError()(1階層なら z.flattenError()) |
.formErrors、.errors | 削除 | undefined | z.flattenError()、.issues |
削除された書き方でも、実行時に警告やエラーは出ませんでした。非推奨の書き方も、警告は出ませんでした。
9. tsc で型検査する
削除された書き方は、型検査で見つけられます。tsconfig.json を作り、tsc を実行します。allowImportingTsExtensions は、import ... from "./schema.ts" のように拡張子をつけて読み込むため、erasableSyntaxOnly は、Node.js の型の除去で動かない書き方(enum など)をエラーにするためです(Node.js のドキュメントの勧めに合わせました)。
tsconfig.json
{
"compilerOptions": {
"target": "esnext",
"module": "nodenext",
"strict": true,
"noEmit": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true
}
}
zrun npx tsc
6-zod3.ts(8,22): error TS2769: No overload matches this call.
The last overload gave the following error.
Object literal may only specify known properties, and 'required_error' does not exist in type '$ZodStringParams'.
6-zod3.ts(13,22): error TS2769: No overload matches this call.
The last overload gave the following error.
Object literal may only specify known properties, and 'errorMap' does not exist in type '$ZodStringParams'.
6-zod3.ts(21,32): error TS2339: Property 'formErrors' does not exist on type 'ZodError<{ a: string; }>'.
6-zod3.ts(21,59): error TS2339: Property 'errors' does not exist on type 'ZodError<{ a: string; }>'.
削除された書き方のうち、required_error、errorMap、.formErrors、.errors がエラーになりました(invalid_type_error は、同じオブジェクトの required_error が先にエラーになったため、別には出ていません)。非推奨の message、.format()、.flatten() はエラーになりません。型の定義では @deprecated がついているので、VS Code などのエディターでは取り消し線で表示されるはずです(エディターでは確かめていません)。
PowerShell の場合
Windows の PowerShell では、関数を作らずに、毎回 docker run を書きます。カレントフォルダは "${PWD}:/app" のように書きます。PowerShell 7.6.10 で、npm install、node 1-issues.ts、node 4-ja.ts、node 5-custom.ts、npx tsc が、Git Bash と同じ結果になりました(ファイルは Git Bash で作ったものをコピーしました)。Windows PowerShell 5.1 では確かめていません。
$IMG = "node:26.13.1-slim@sha256:abe7e5a82b61a8ef67b315b85497c9e65173387ccf2f4a029248184b8e020be5"
docker run --rm -v "${PWD}:/app" -w /app $IMG npm install zod@4.6.7 typescript@7.0.2
docker run --rm -v "${PWD}:/app" -w /app $IMG node 4-ja.ts
✖ 小さすぎる値: stringは1文字以上である必要があります
→ at customer.name
✖ 無効なメールアドレス
→ at customer.email
✖ 無効な入力: stringが期待されましたが、数値が入力されました
→ at tags[1]
✖ 無効な入力: stringが期待されましたが、数値が入力されました
→ at items[1].sku
✖ 小さすぎる値: numberは0より大きい必要があります
→ at items[1].quantity
ハマった点
max を超えた配列は、要素の中身を調べない
最初は、tags に ["a", "b", "c", 4] を入れて試しました。すると、max(3) を超えたエラーだけが出て、4つ目の数値のエラーが出ませんでした。
7-max.ts
import * as z from "zod";
const Tags = z.array(z.string()).max(3);
for (const value of [["a", 42], ["a", "b", "c", 42]]) {
const r = Tags.safeParse(value);
console.log(JSON.stringify(value), "=>", r.success ? "OK" : r.error.issues.map((i) => `${i.code} ${JSON.stringify(i.path)}`));
}
zrun node 7-max.ts
["a",42] => [ 'invalid_type [1]' ]
["a","b","c",42] => [ 'too_big []' ]
インストールされた zod/v4/core/schemas.js では、配列の長さが max を超えると、要素を調べずにそのエラーだけを返していました(capSize という処理)。長すぎる配列をすべて調べないための作りと考えられます(推測)。長さのエラーを直すと、次に要素のエラーが出てくることがあります。
削除された書き方は、実行しても気づけない
手順8のとおり、required_error などは、実行してもエラーにならず、メッセージが英語の標準のものに戻るだけでした。テストでメッセージを確かめていなければ、移行したことに気づけません。手順9の型検査を通すのが確実です。
後片付け
docker run に --rm をつけているので、コンテナは残りません。作業用のフォルダ(zod-errors)を消せば終わりです。node:26.13.1-slim のイメージが要らなければ、docker image rm で消します。
まとめ
- エラーの元のデータは
issues。表示用には、入れ子ならz.treeifyError、ログならz.prettifyError、1階層ならz.flattenError。 - 日本語は
z.config(z.locales.ja())。項目ごとに決めるならerrorに文字列か関数。 - Zod 3 からの移行では、
required_error、invalid_type_error、errorMapが黙って無視される。tscの型検査で見つける。
参考URL
- Formatting errors | Zod(
treeifyError、prettifyError、flattenError、非推奨のformatError) - Customizing errors | Zod(
error、優先順位、ロケール、reportInput) - Migration guide | Zod(Zod 3 からの変更点)
- Modules: TypeScript | Node.js(型の除去、勧める
tsconfig.jsonの設定) - Announcing TypeScript 7.0 – TypeScript
- Troubleshoot topics for Docker Desktop | Docker Docs(Git Bash のパス変換)


コメント