5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

はじめに

最近 Zod 4 が npm に公開されました。

この記事では、Zod 4 の個人的に気になった変更点についてまとめていきたいと思います。

Zod とは?

Zod とは、TypeScript 向けのスキーマ定義・バリデーションライブラリです。スキーマを定義すると、そのスキーマをもとに TypeScript の型も定義することができます。

気になった変更点

以下では、公式ドキュメントの Zod 4 の概要や変更点をもとに、個人的に注目したポイントを紹介します。

JSON Schema への変換

z.toJSONSchema() 関数を使うことで、定義したスキーマを JSON Schema に変換できるようになりました。

import * as z from "zod";

const mySchema = z.object({name: z.string(), points: z.number()});
 
z.toJSONSchema(mySchema);
// => {
//   type: "object",
//   properties: {
//     name: {type: "string"},
//     points: {type: "number"},
//   },
//   required: ["name", "points"],
// }

( https://zod.dev/v4?id=json-schema-conversion からの引用 )

ファイル用のスキーマ

ファイルのサイズやMIMEでバリデーションできるようになりました。

const fileSchema = z.file();
 
fileSchema.min(10_000); // minimum .size (bytes)
fileSchema.max(1_000_000); // maximum .size (bytes)
fileSchema.mime(["image/png"]); // MIME type

( https://zod.dev/v4?id=file-schemas からの引用)

i18n の対応

エラーメッセージの言語を指定できるようになりました。

import * as z from "zod";
 
// configure English locale (default)
z.config(z.locales.en());

( https://zod.dev/v4?id=internationalization からの引用)

現在は英語のみの対応になっていますが、今後サポートされる言語が拡充されていくそうです。わざわざ指定せずに済むようになるので便利ですね。

文字列のフォーマット

Zod では、文字列のバリデーションを行うためのフォーマットがいくつか用意されています。Zod 4 では、よりシンプルに扱えるようになりました。

// Zod 3
z.string().email();
z.string().url();
z.string().ip() // Zod 4 では廃止

// Zod 4
z.email();
z.url();
z.ipv4()
z.ipv6()

( 参考:https://zod.dev/v4/changelog?id=zstring-updates)

z.string().email()などは非推奨ですが、現状は動作します。将来のメジャーバージョンで廃止予定です

エラーのカスタマイズ

今まで message パラメータでエラーメッセージを渡していましたが、それが非推奨になり、今後は error パラメータで渡すようになりました。

// Zod 3
z.string().min(5, { message: "Too short." });

// Zod 4
z.string().min(5, { error: "Too short." });

また、invalid_type_errorrequired_errorerrorMap は廃止され、 error に統合されました。これにより、よりシンプルに記述できるようになりました。

// Zod 3
z.string({ 
  required_error: "This field is required",
  invalid_type_error: "Not a string", 
});

z.string({
  errorMap: (issue, ctx) => {
    if (issue.code === "too_small") {
      return { message: `Value must be >${issue.minimum}` };
    }
    return { message: ctx.defaultError };
  },
});

// Zod 4
z.string({ 
  error: (issue) => issue.input === undefined 
    ? "This field is required" 
    : "Not a string" 
});

z.string().min(5, {
  error: (issue) => {
    if (issue.code === "too_small") {
      return `Value must be >${issue.minimum}`
    }
  },
});

(https://zod.dev/v4/changelog?id=error-customization から引用)

issue オブジェクトってどうやって使うんだ?」ってなったのですが、この辺りをうまく使うと柔軟にエラーに対応できそうです。

z.string({
  error: (iss) => {
    iss.code; // the issue code
    iss.input; // the input data
    iss.inst; // the schema/check that originated this issue
    iss.path; // the path of the error
  },
});

( https://zod.dev/error-customization?id=the-error-param から引用)

さいごに

今回は、Zod 4 の個人的に気になった変更点についてまとめてみました。
次は、実際に Zod 4 を使って何かをやってみようと思います。

5
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?