zod - 静的型推論を使用したTypeScriptファーストのスキーマ検証

(TypeScript-first schema validation with static type inference)

Created at: 2020-03-08 04:59:08
Language: TypeScript
License: MIT

ゾッドロゴ

ゾッド

https://zod.dev
静的型推論によるTypeScriptファーストのスキーマ検証


ゾッドCIステータス コリン・マクドネルによって作成されました ライセンス ティッカー 星 不和サーバー



これらのドキュメントは中国語に翻訳されています。

目次

紹介

Zod は TypeScript 初のスキーマ宣言および検証ライブラリです。ここでは、"schema" という用語を使用して、単純な入れ子になったオブジェクトから複雑な入れ子になったオブジェクトまで、あらゆるデータ型を広く指しています。

string

Zodは、可能な限り開発者に優しいように設計されています。目標は、重複する型宣言を排除することです。Zodでは、バリデーターを一度宣言すると、Zodは自動的に静的TypeScript型を推論します。単純な型を複雑なデータ構造に簡単に構成できます。

他のいくつかの素晴らしい側面:

  • ゼロ依存関係
  • ノード.jsおよびすべての最新のブラウザで動作します
  • 小さい:8kb縮小+圧縮
  • 不変:メソッド(例)は新しいインスタンスを返します
    .optional()
  • 簡潔でチェーン可能なインターフェース
  • 機能的アプローチ:解析、検証しない
  • プレーンなJavaScriptでも動作します!TypeScript を使用する必要はありません。

スポンサー

あらゆるレベルでのスポンサーシップが高く評価され、奨励されています。個々の開発者の場合は、カップ オブ コーヒー レベルを検討してください。Zodを使用して有料製品を構築した場合は、表彰台の層の1つを検討してください。

アストロ
アストロアストロ
ビルド

Astroは、最新のWeb用の新しい種類の静的
サイトビルダーです。
強力な開発者エクスペリエンスと軽量出力の融合


グローウォレット
glow.app

あなたの新しいお気に入りの
ソラナ財布。

デレタイプロゴ
デレタイプ
deletype.com
プロキシロゴ
プロキシ proxy.com

数値ロゴ
数値
numeric.io
スナップレットのロゴ
スナップレット
snaplet.dev
マルカートパートナーズ
マルカートパートナーズ marcatopartners.com

インターバル interval.com

経験豊富なソフトウェア
seasoned.cc
バンブークリエイティブのロゴ
バンブークリエイティブ
bamboocreative.nz

青銅


ブランドンベイヤー
@flybayerブリッツの作成者.js

イジー・ブラベツ
@brabeji

アレックス・ヨハンソン
@alexdotjs
代替可能なシステムのロゴ
代替可能なシステム 代替可能.システム


適応可能な
adaptable.io
アバナウォレットのロゴ
アバナウォレット
avanawallet.com
ソラナ非カストディアルウォレット

生態系

Zodの上に構築されている、またはZodをネイティブにサポートしているツールが増えています。Zodの上にツールやライブラリを構築したことがある場合は、Twitterでそれについて教えてください、またはディスカッションを開始してください。以下に追加してツイートします。

リソース

API ライブラリ

  • tRPC: GraphQL を使用せずにエンドツーエンドのタイプセーフな API を構築します。
  • @anatine/zod-nestjs: NestJS プロジェクトで Zod を使用するためのヘルパーメソッド。
  • zod エンドポイント: コントラクト ファーストの厳密に型指定されたエンドポイントと Zod。OpenAPI 互換です。
  • ドメイン関数: 構成可能な関数を使用して、ビジネス ロジックをフレームワークから切り離します。Zodスキーマを利用したエンドツーエンドのファーストクラスの型推論を備えています。
  • @zodios/core: axios と zod に裏打ちされたランタイムおよびコンパイル時の検証を備えたタイプスクリプト API クライアント。
  • express-zod-api: I/O スキーマ検証とカスタム ミドルウェアを使用して、Express ベースの API を構築します。

フォームの統合

  • react-hook-form: React Hook Form用のファーストパーティのZodリゾルバ。
  • zod-validation-error: s からユーザーフレンドリーなエラーメッセージを生成する
    ZodError
  • zod-formik-adapter: コミュニティが管理する Zod 用の Formik アダプタ。
  • react-zorm: Zod を使用した React のスタンドアロン生成と検証。
    <form>
  • zodix: Remix loaders and actions の FormData と URLSearchParams 用の Zod ユーティリティ。
  • formik-validator-zod: Formik で Zod を単純化する、Formik 準拠のバリデータライブラリ。
  • zod-i18n-map: Zod のエラーメッセージを翻訳するのに便利です。
  • @modularフォーム/ソリッド: 検証用の Zod をサポートする SolidJS 用のモジュラーフォームライブラリ。

ゾッドからXへ

  • zod-to-ts: Zod スキーマからタイプスクリプト定義を生成します。
  • zod-to-json-schema: Zod スキーマを JSON スキーマに変換します。
  • @anatine/zod-openapi: Zod スキーマを OpenAPI v3.x に変換します。
    SchemaObject
  • zod-fast-check: Zod スキーマから任意のものを生成します。
    fast-check
  • zod-dto: Zod スキーマからネスト.js DTO を生成します。
  • fastify-type-provider-zod: Zod スキーマから Fastify 型プロバイダーを作成します。
  • zod-to-openapi: スキーマ、エンドポイント、パラメータを含む完全なOpenAPI(Swagger)ドキュメントをZodから生成します。
  • nestjs-graphql-zod: Zod スキーマから NestJS GraphQL モデルクラスを生成します。Zod スキーマを操作する GraphQL メソッドデコレータを提供します。

X からゾッドへ

あざける

ゾッドを搭載

  • slonik:ノード.js強力なゾッド統合を備えたPostgresクライアント。
  • soly: zod を使用して CLI アプリケーションを作成します。
  • zod-xlsx: Zod スキーマを使用する xlsx ベースのリソースバリデーター。
  • znv: Zod スキーマを使用したノード.jsのタイプセーフな環境の解析と検証

取り付け

必要条件

  • タイプスクリプト4.5+!

  • でモードを有効にする必要があります。これは、すべての TypeScript プロジェクトのベスト プラクティスです。

    strict
    tsconfig.json

    // tsconfig.json
    {
      // ...
      "compilerOptions": {
        // ...
        "strict": true
      }
    }

差出人 (ノード/ブン)
npm

npm install zod       # npm
yarn add zod          # yarn
bun add zod           # bun
pnpm add zod          # pnpm

(デノ)から
deno.land/x

ノードとは異なり、DenoはNPMのようなパッケージマネージャーではなく、直接URLインポートに依存しています。Zod は deno.land/x で入手できます。最新バージョンは次のようにインポートできます。

import { z } from "https://deno.land/x/zod/mod.ts";

特定のバージョンを指定することもできます。

import { z } from "https://deno.land/x/zod@v3.16.1/mod.ts";

この README の残りの部分では、npm を使用してパッケージから直接インポートしていることを前提としています。

"zod"

基本的な使い方

単純な文字列スキーマの作成

import { z } from "zod";

// creating a schema for strings
const mySchema = z.string();

// parsing
mySchema.parse("tuna"); // => "tuna"
mySchema.parse(12); // => throws ZodError

// "safe" parsing (doesn't throw error if validation fails)
mySchema.safeParse("tuna"); // => { success: true; data: "tuna" }
mySchema.safeParse(12); // => { success: false; error: ZodError }

オブジェクトスキーマの作成

import { z } from "zod";

const User = z.object({
  username: z.string(),
});

User.parse({ username: "Ludwig" });

// extract the inferred type
type User = z.infer<typeof User>;
// { username: string }

プリミティブ

import { z } from "zod";

// primitive values
z.string();
z.number();
z.bigint();
z.boolean();
z.date();
z.symbol();

// empty types
z.undefined();
z.null();
z.void(); // accepts undefined

// catch-all types
// allows any value
z.any();
z.unknown();

// never type
// allows no values
z.never();

リテラル

const tuna = z.literal("tuna");
const twelve = z.literal(12);
const twobig = z.literal(2n); // bigint literal
const tru = z.literal(true);

const terrificSymbol = Symbol("terrific");
const terrific = z.literal(terrificSymbol);

// retrieve literal value
tuna.value; // "tuna"

現在、Zod では日付リテラルはサポートされていません。この機能の使用例がある場合は、問題を報告してください。

ストリングス

Zod には、文字列固有の検証がいくつか含まれています。

z.string().max(5);
z.string().min(5);
z.string().length(5);
z.string().email();
z.string().url();
z.string().uuid();
z.string().cuid();
z.string().regex(regex);
z.string().startsWith(string);
z.string().endsWith(string);
z.string().trim(); // trim whitespace
z.string().datetime(); // defaults to UTC, see below for options

validator.jsをチェックして、絞り込みと組み合わせて使用できる他の便利な文字列検証関数の束を確認してください。

文字列スキーマを作成する際の一般的なエラー メッセージをカスタマイズできます。

const name = z.string({
  required_error: "Name is required",
  invalid_type_error: "Name must be a string",
});

検証メソッドを使用する場合は、追加の引数を渡して、カスタム エラー メッセージを提供できます。

z.string().min(5, { message: "Must be 5 or more characters long" });
z.string().max(5, { message: "Must be 5 or fewer characters long" });
z.string().length(5, { message: "Must be exactly 5 characters long" });
z.string().email({ message: "Invalid email address" });
z.string().url({ message: "Invalid url" });
z.string().uuid({ message: "Invalid UUID" });
z.string().startsWith("https://", { message: "Must provide secure URL" });
z.string().endsWith(".com", { message: "Only .com domains allowed" });
z.string().datetime({ message: "Invalid datetime string! Must be UTC." });

プリミティブの強制

Zod は、プリミティブ値を強制するためのより便利な方法を提供するようになりました。

const schema = z.coerce.string();
schema.parse("tuna"); // => "tuna"
schema.parse(12); // => "12"
schema.parse(true); // => "true"

解析ステップでは、入力は、データを文字列に強制するための JavaScript 組み込み関数を介して渡されます。返されるスキーマはインスタンスであるため、すべての文字列メソッドを使用できます。

String()
ZodString

z.coerce.string().email().min(5);

すべてのプリミティブ型は強制型変換をサポートしています。

z.coerce.string(); // String(input)
z.coerce.number(); // Number(input)
z.coerce.boolean(); // Boolean(input)
z.coerce.bigint(); // BigInt(input)
z.coerce.date(); // new Date(input)

ブール型強制型変換

ゾッドのブール強制は非常に簡単です!値を関数に渡します。真実の値は に解決され、偽の値は に解決されます。

Boolean(value)
true
false

z.coerce.boolean().parse("tuna"); // => true
z.coerce.boolean().parse("true"); // => true
z.coerce.boolean().parse("false"); // => true
z.coerce.boolean().parse(1); // => true
z.coerce.boolean().parse([]); // => true

z.coerce.boolean().parse(0); // => false
z.coerce.boolean().parse(undefined); // => false
z.coerce.boolean().parse(null); // => false

日時の検証

このメソッドはデフォルトでUTC検証になります:任意の秒未満の10進精度を持つタイムゾーンオフセットはありません。

z.string().datetime()

const datetime = z.string().datetime();

datetime.parse("2020-01-01T00:00:00Z"); // pass
datetime.parse("2020-01-01T00:00:00.123Z"); // pass
datetime.parse("2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision)
datetime.parse("2020-01-01T00:00:00+02:00"); // fail (no offsets allowed)

タイムゾーンオフセットは、オプションをに設定することで許可できます。

offset
true

const datetime = z.string().datetime({ offset: true });

datetime.parse("2020-01-01T00:00:00+02:00"); // pass
datetime.parse("2020-01-01T00:00:00.123+02:00"); // pass (millis optional)
datetime.parse("2020-01-01T00:00:00Z"); // pass (Z still supported)

さらに、許容される .既定では、任意の秒未満の精度がサポートされています (ただし省略可能)。

precision

const datetime = z.string().datetime({ precision: 3 });

datetime.parse("2020-01-01T00:00:00.123Z"); // pass
datetime.parse("2020-01-01T00:00:00Z"); // fail
datetime.parse("2020-01-01T00:00:00.123456Z"); // fail

番号

数値スキーマの作成時に特定のエラー メッセージをカスタマイズできます。

const age = z.number({
  required_error: "Age is required",
  invalid_type_error: "Age must be a number",
});

Zod には、いくつかの数値固有の検証が含まれています。

z.number().gt(5);
z.number().gte(5); // alias .min(5)
z.number().lt(5);
z.number().lte(5); // alias .max(5)

z.number().int(); // value must be an integer

z.number().positive(); //     > 0
z.number().nonnegative(); //  >= 0
z.number().negative(); //     < 0
z.number().nonpositive(); //  <= 0

z.number().multipleOf(5); // Evenly divisible by 5. Alias .step(5)

z.number().finite(); // value must be finite, not Infinity or -Infinity

必要に応じて、2 番目の引数を渡して、カスタム エラー メッセージを指定できます。

z.number().lte(5, { message: "this👏is👏too👏big" });

ナン

nanスキーマの作成時に特定のエラーメッセージをカスタマイズできます。

const isNaN = z.nan({
  required_error: "isNaN is required",
  invalid_type_error: "isNaN must be not a number",
});

ブール

ブールスキーマの作成時に特定のエラーメッセージをカスタマイズできます。

const isActive = z.boolean({
  required_error: "isActive is required",
  invalid_type_error: "isActive must be a boolean",
});

日付

インスタンスを検証するには、z.date() を使用します。

Date

z.date().safeParse(new Date()); // success: true
z.date().safeParse("2022-01-12T00:00:00.000Z"); // success: false

日付スキーマの作成時に特定のエラーメッセージをカスタマイズできます。

const myDateSchema = z.date({
  required_error: "Please select a date and time",
  invalid_type_error: "That's not a date!",
});

Zod には、日付固有の検証がいくつか用意されています。

z.date().min(new Date("1900-01-01"), { message: "Too old" });
z.date().max(new Date(), { message: "Too young!" });

日付文字列のサポート

日付文字列または日付文字列のいずれかを受け入れるスキーマを記述するには、z.preprocess を使用します。

Date

const dateSchema = z.preprocess((arg) => {
  if (typeof arg == "string" || arg instanceof Date) return new Date(arg);
}, z.date());
type DateSchema = z.infer<typeof dateSchema>;
// type DateSchema = Date

dateSchema.safeParse(new Date("1/12/22")); // success: true
dateSchema.safeParse("2022-01-12T00:00:00.000Z"); // success: true

ゾッド列挙型

const FishEnum = z.enum(["Salmon", "Tuna", "Trout"]);
type FishEnum = z.infer<typeof FishEnum>;
// 'Salmon' | 'Tuna' | 'Trout'

z.enum
は、許容される文字列値の固定セットを使用してスキーマを宣言する Zod ネイティブの方法です。値の配列を直接 に渡します。または、列挙値を文字列のタプルとして定義するために使用します。詳細については、const アサーションのドキュメントを参照してください
z.enum()
as const

const VALUES = ["Salmon", "Tuna", "Trout"] as const;
const FishEnum = z.enum(VALUES);

Zodは各要素の正確な値を推測できないため、これは許可されていません。

const fish = ["Salmon", "Tuna", "Trout"];
const FishEnum = z.enum(fish);

オートコンプリート

Zod 列挙型でオートコンプリートを取得するには、スキーマのプロパティを使用します。

.enum

FishEnum.enum.Salmon; // => autocompletes

FishEnum.enum;
/*
=> {
  Salmon: "Salmon",
  Tuna: "Tuna",
  Trout: "Trout",
}
*/

オプションのリストをプロパティを持つタプルとして取得することもできます。

.options

FishEnum.options; // ["Salmon", "Tuna", "Trout"]);

ネイティブ列挙型

Zod 列挙型は、列挙型を定義および検証するための推奨されるアプローチです。ただし、サードパーティのライブラリの列挙型に対して検証する必要がある場合(または既存の列挙型を書き直したくない場合)は、.

z.nativeEnum()

数値列挙型

enum Fruits {
  Apple,
  Banana,
}

const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // Fruits

FruitEnum.parse(Fruits.Apple); // passes
FruitEnum.parse(Fruits.Banana); // passes
FruitEnum.parse(0); // passes
FruitEnum.parse(1); // passes
FruitEnum.parse(3); // fails

文字列列挙型

enum Fruits {
  Apple = "apple",
  Banana = "banana",
  Cantaloupe, // you can mix numerical and string enums
}

const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // Fruits

FruitEnum.parse(Fruits.Apple); // passes
FruitEnum.parse(Fruits.Cantaloupe); // passes
FruitEnum.parse("apple"); // passes
FruitEnum.parse("banana"); // passes
FruitEnum.parse(0); // passes
FruitEnum.parse("Cantaloupe"); // fails

Const 列挙型

この関数はオブジェクトに対しても機能します。⚠️ 必要なタイプスクリプト3.4+!

.nativeEnum()
as const
as const

const Fruits = {
  Apple: "apple",
  Banana: "banana",
  Cantaloupe: 3,
} as const;

const FruitEnum = z.nativeEnum(Fruits);
type FruitEnum = z.infer<typeof FruitEnum>; // "apple" | "banana" | 3

FruitEnum.parse("apple"); // passes
FruitEnum.parse("banana"); // passes
FruitEnum.parse(3); // passes
FruitEnum.parse("Cantaloupe"); // fails

基になるオブジェクトには、次のプロパティを使用してアクセスできます。

.enum

FruitEnum.enum.Apple; // "apple"

オプション

任意のスキーマをオプションにすることができます。これにより、スキーマがインスタンスにラップされ、結果が返されます。

z.optional()
ZodOptional

const schema = z.optional(z.string());

schema.parse(undefined); // => returns undefined
type A = z.infer<typeof schema>; // string | undefined

便宜上、既存のスキーマでメソッドを呼び出すこともできます。

.optional()

const user = z.object({
  username: z.string().optional(),
});
type C = z.infer<typeof user>; // { username?: string | undefined };

ラップされたスキーマは、を使用してインスタンスから抽出できます。

ZodOptional
.unwrap()

const stringSchema = z.string();
const optionalString = stringSchema.optional();
optionalString.unwrap() === stringSchema; // true

null 許容値

同様に、 を使用して null 許容型を作成できます。

z.nullable()

const nullableString = z.nullable(z.string());
nullableString.parse("asdf"); // => "asdf"
nullableString.parse(null); // => null

または、メソッドを使用します。

.nullable()

const E = z.string().nullable(); // equivalent to nullableString
type E = z.infer<typeof E>; // string | null

を使用して内部スキーマを抽出します。

.unwrap()

const stringSchema = z.string();
const nullableString = stringSchema.nullable();
nullableString.unwrap() === stringSchema; // true

オブジェクト

// all properties are required by default
const Dog = z.object({
  name: z.string(),
  age: z.number(),
});

// extract the inferred type like this
type Dog = z.infer<typeof Dog>;

// equivalent to:
type Dog = {
  name: string;
  age: number;
};

.shape

特定のキーのスキーマにアクセスするために使用します。

.shape

Dog.shape.name; // => string schema
Dog.shape.age; // => number schema

.keyof

オブジェクト スキーマのキーからスキーマを作成するために使用します。

.keyof
ZodEnum

const keySchema = Dog.keyof();
keySchema; // ZodEnum<["name", "age"]>

.extend

このメソッドを使用して、オブジェクトスキーマにフィールドを追加できます。

.extend

const DogWithBreed = Dog.extend({
  breed: z.string(),
});

フィールドを上書きするために使用できます!この力に注意してください!

.extend

.merge

と同等です。

A.extend(B.shape)

const BaseTeacher = z.object({ students: z.array(z.string()) });
const HasID = z.object({ id: z.string() });

const Teacher = BaseTeacher.merge(HasID);
type Teacher = z.infer<typeof Teacher>; // => { students: string[], id: string }

2 つのスキーマがキーを共有している場合、B のプロパティは A のプロパティをオーバーライドします。返されるスキーマは、"unknownKeys" ポリシー (ストリップ/ストリクト/パススルー) と B のキャッチオール スキーマも継承します。

.pick/.omit

TypeScript の組み込み型とユーティリティ型に触発され、すべての Zod オブジェクト スキーマには、変更されたバージョンを返すメソッドがあります。このレシピスキーマを考えてみましょう。

Pick
Omit
.pick
.omit

const Recipe = z.object({
  id: z.string(),
  name: z.string(),
  ingredients: z.array(z.string()),
});

特定のキーのみを保持するには、 を使用します。

.pick

const JustTheName = Recipe.pick({ name: true });
type JustTheName = z.infer<typeof JustTheName>;
// => { name: string }

特定のキーを削除するには、 を使用します。

.omit

const NoIDRecipe = Recipe.omit({ id: true });

type NoIDRecipe = z.infer<typeof NoIDRecipe>;
// => { name: string, ingredients: string[] }

.partial

組み込みの TypeScript ユーティリティの種類 Partial に触発されたこのメソッドは、すべてのプロパティを省略可能にします。

.partial

このオブジェクトから開始します。

const user = z.object({
  email: z.string()
  username: z.string(),
});
// { email: string; username: string }

部分バージョンを作成できます。

const partialUser = user.partial();
// { email?: string | undefined; username?: string | undefined }

オプションにするプロパティを指定することもできます。

const optionalEmail = user.partial({
  email: true,
});
/*
{
  email?: string | undefined;
  username: string
}
*/

.deepPartial

この方法は浅く、1レベルの深さしか適用されません。「深い」バージョンもあります。

.partial

const user = z.object({
  username: z.string(),
  location: z.object({
    latitude: z.number(),
    longitude: z.number(),
  }),
  strings: z.array(z.object({ value: z.string() })),
});

const deepPartialUser = user.deepPartial();

/*
{
  username?: string | undefined,
  location?: {
    latitude?: number | undefined;
    longitude?: number | undefined;
  } | undefined,
  strings?: { value?: string}[]
}
*/

重要な制限:深いパーシャルは、オブジェクト、配列、およびタプルの階層でのみ期待どおりに機能します。

.required

メソッドとは異なり、このメソッドはすべてのプロパティを必須にします。

.partial
.required

このオブジェクトから開始します。

const user = z.object({
  email: z.string()
  username: z.string(),
}).partial();
// { email?: string | undefined; username?: string | undefined }

必要なバージョンを作成できます。

const requiredUser = user.required();
// { email: string; username: string }

必須にするプロパティを指定することもできます。

const requiredEmail = user.required({
  email: true,
});
/*
{
  email: string;
  username?: string | undefined;
}
*/

.passthrough

デフォルトでは、Zod オブジェクトスキーマは解析中に認識されないキーを削除します。

const person = z.object({
  name: z.string(),
});

person.parse({
  name: "bob dylan",
  extraKey: 61,
});
// => { name: "bob dylan" }
// extraKey has been stripped

代わりに、不明なキーを渡す場合は、.

.passthrough()

person.passthrough().parse({
  name: "bob dylan",
  extraKey: 61,
});
// => { name: "bob dylan", extraKey: 61 }

.strict

デフォルトでは、Zod オブジェクトスキーマは解析中に認識されないキーを削除します。不明なキーは で禁止できます。入力に不明なキーがある場合、Zodはエラーをスローします。

.strict()

const person = z
  .object({
    name: z.string(),
  })
  .strict();

person.parse({
  name: "bob dylan",
  extraKey: 61,
});
// => throws ZodError

.strip

このメソッドを使用して、オブジェクト スキーマを既定の動作 (認識されないキーの削除) にリセットできます。

.strip

.catchall

"catchall" スキーマをオブジェクト スキーマに渡すことができます。すべての不明なキーがそれに対して検証されます。

const person = z
  .object({
    name: z.string(),
  })
  .catchall(z.number());

person.parse({
  name: "bob dylan",
  validExtraKey: 61, // works fine
});

person.parse({
  name: "bob dylan",
  validExtraKey: false, // fails
});
// => throws ZodError

を使用すると、または が削除されます。これで、すべてのキーが「既知」と見なされます。

.catchall()
.passthrough()
.strip()
.strict()

配列

const stringArray = z.array(z.string());

// equivalent
const stringArray = z.string().array();

方法に注意してください。新しいインスタンスを返します。つまり、メソッドを呼び出す順序が重要です。例えば:

.array()
ZodArray

z.string().optional().array(); // (string | undefined)[]
z.string().array().optional(); // string[] | undefined

.element

配列の要素のスキーマにアクセスするために使用します。

.element

stringArray.element; // => string schema

.nonempty

配列に少なくとも 1 つの要素が含まれるようにするには、.

.nonempty()

const nonEmptyStrings = z.string().array().nonempty();
// the inferred type is now
// [string, ...string[]]

nonEmptyStrings.parse([]); // throws: "Array cannot be empty"
nonEmptyStrings.parse(["Ariana Grande"]); // passes

オプションで、カスタムエラーメッセージを指定できます。

// optional custom error message
const nonEmptyStrings = z.string().array().nonempty({
  message: "Can't be empty!",
});

.min/.max/.length

z.string().array().min(5); // must contain 5 or more items
z.string().array().max(5); // must contain 5 or fewer items
z.string().array().length(5); // must contain 5 items exactly

これらのメソッドとは異なり、推論された型は変更されません。

.nonempty()

配列とは異なり、タプルには固定数の要素があり、各要素は異なる型を持つことができます。

const athleteSchema = z.tuple([
  z.string(), // name
  z.number(), // jersey number
  z.object({
    pointsScored: z.number(),
  }), // statistics
]);

type Athlete = z.infer<typeof athleteSchema>;
// type Athlete = [string, number, { pointsScored: number }]

可変個引数 ("rest") をメソッドと共に追加できます。

.rest

const variadicTuple = z.tuple([z.string()]).rest(z.number());
const result = variadicTuple.parse(["hello", 1, 2, 3]);
// => [string, ...number[]];

労働 組合

Zod には、"OR" 型を作成するための組み込みメソッドが含まれています。

z.union

const stringOrNumber = z.union([z.string(), z.number()]);

stringOrNumber.parse("foo"); // passes
stringOrNumber.parse(14); // passes

Zodは、各「オプション」に対して入力を順番にテストし、正常に検証された最初の値を返します。

便宜上、次の方法を使用することもできます。

.or

const stringOrNumber = z.string().or(z.number());

差別された組合

判別共用体は、すべて特定のキーを共有するオブジェクト スキーマの和集合です。

type MyUnion =
  | { status: "success"; data: string }
  | { status: "failed"; error: Error };

そのような共用体は、メソッドで表すことができます。これにより、Zod は識別子キー (上記の例) をチェックして、入力の解析に使用するスキーマを決定できるため、より高速な評価が可能になります。これにより、解析がより効率的になり、Zodがよりわかりやすいエラーを報告できるようになります。

z.discriminatedUnion
status

基本的な和集合方法では、入力は指定された各「オプション」に対してテストされ、無効な場合は、すべての「オプション」の問題がzodエラーに表示されます。一方、判別共用体では、「オプション」の1つだけを選択し、それに対してテストし、この「オプション」に関連する問題のみを表示できます。

const myUnion = z.discriminatedUnion("status", [
  z.object({ status: z.literal("success"), data: z.string() }),
  z.object({ status: z.literal("failed"), error: z.instanceof(Error) }),
]);

myUnion.parse({ type: "success", data: "yippie ki yay" });

レコード スキーマは、 などの型を検証するために使用されます。

{ [k: string]: number }

オブジェクトの値を何らかのスキーマに対して検証したいが、キーを気にしない場合は、

z.record(valueType)

const NumberCache = z.record(z.number());

type NumberCache = z.infer<typeof NumberCache>;
// => { [k: string]: number }

これは、ID で項目を格納またはキャッシュする場合に特に便利です。

const userStore: UserStore = {};

userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
  name: "Carlotta",
}; // passes

userStore["77d2586b-9e8e-4ecf-8b21-ea7e0530eadd"] = {
  whatever: "Ice cream sundae",
}; // TypeError

レコード・キー・タイプ

キーと値の両方を検証する場合は、次を使用します。

z.record(keyType, valueType)

const NoEmptyKeysSchema = z.record(z.string().min(1), z.number());
NoEmptyKeysSchema.parse({ count: 1 }); // => { 'count': 1 }
NoEmptyKeysSchema.parse({ "": 1 }); // fails

(2つの引数を渡すとき、valueTypeが2番目の引数であることに注意してください)

数字キーに関する注意

は数値キータイプを受け入れることができ、TypeScriptの組み込みレコードタイプは ですが、ZodでTypeScriptタイプを表すことは困難です。

z.record(keyType, valueType)
Record<KeyType, ValueType>
Record<number, any>

結局のところ、TypeScriptの動作は少し直感的ではありません。

[k: number]

const testMap: { [k: number]: string } = {
  1: "one",
};

for (const key in testMap) {
  console.log(`${key}: ${typeof key}`);
}
// prints: `1: string`

ご覧のとおり、JavaScript はすべてのオブジェクトキーを内部で文字列に自動的にキャストします。Zodは静的型とランタイム型の間のギャップを埋めようとしているので、ランタイムJavaScriptには数値キーのようなものがないため、数値キーを使用してレコードスキーマを作成する方法を提供することは意味がありません。

マップ

const stringNumberMap = z.map(z.string(), z.number());

type StringNumberMap = z.infer<typeof stringNumberMap>;
// type StringNumberMap = Map<string, number>

設定

const numberSet = z.set(z.number());
type NumberSet = z.infer<typeof numberSet>;
// type NumberSet = Set<number>

セットスキーマは、次のユーティリティメソッドでさらに制約できます。

z.set(z.string()).nonempty(); // must contain at least one item
z.set(z.string()).min(5); // must contain 5 or more items
z.set(z.string()).max(5); // must contain 5 or fewer items
z.set(z.string()).size(5); // must contain 5 items exactly

交差点

交差は、"論理 AND" 型を作成する場合に便利です。これは、2 つのオブジェクト タイプを交差させる場合に便利です。

const Person = z.object({
  name: z.string(),
});

const Employee = z.object({
  role: z.string(),
});

const EmployedPerson = z.intersection(Person, Employee);

// equivalent to:
const EmployedPerson = Person.and(Employee);

Though in many cases, it is recommended to use to merge two objects. The method returns a new instance, whereas returns a less useful instance that lacks common object methods like and .

A.merge(B)
.merge
ZodObject
A.and(B)
ZodIntersection
pick
omit

const a = z.union([z.number(), z.string()]);
const b = z.union([z.number(), z.boolean()]);
const c = z.intersection(a, b);

type c = z.infer<typeof c>; // => number

Recursive types

You can define a recursive schema in Zod, but because of a limitation of TypeScript, their type can't be statically inferred. Instead you'll need to define the type definition manually, and provide it to Zod as a "type hint".

interface Category {
  name: string;
  subcategories: Category[];
}

// cast to z.ZodType<Category>
const Category: z.ZodType<Category> = z.lazy(() =>
  z.object({
    name: z.string(),
    subcategories: z.array(Category),
  })
);

Category.parse({
  name: "People",
  subcategories: [
    {
      name: "Politicians",
      subcategories: [{ name: "Presidents", subcategories: [] }],
    },
  ],
}); // passes

Unfortunately this code is a bit duplicative, since you're declaring the types twice: once in the interface and again in the Zod definition.

JSON type

If you want to validate any JSON value, you can use the snippet below.

const literalSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
type Literal = z.infer<typeof literalSchema>;
type Json = Literal | { [key: string]: Json } | Json[];
const jsonSchema: z.ZodType<Json> = z.lazy(() =>
  z.union([literalSchema, z.array(jsonSchema), z.record(jsonSchema)])
);

jsonSchema.parse(data);

Thanks to ggoodman for suggesting this.

Cyclical objects

Despite supporting recursive schemas, passing cyclical data into Zod will cause an infinite loop.

Promises

const numberPromise = z.promise(z.number());

"Parsing" works a little differently with promise schemas. Validation happens in two parts:

  1. Zod synchronously checks that the input is an instance of Promise (i.e. an object with and methods.).
    .then
    .catch
  2. Zod uses to attach an additional validation step onto the existing Promise. You'll have to use on the returned Promise to handle validation failures.
    .then
    .catch
numberPromise.parse("tuna");
// ZodError: Non-Promise type: string

numberPromise.parse(Promise.resolve("tuna"));
// => Promise<number>

const test = async () => {
  await numberPromise.parse(Promise.resolve("tuna"));
  // ZodError: Non-number type: string

  await numberPromise.parse(Promise.resolve(3.14));
  // => 3.14
};

Instanceof

You can use to check that the input is an instance of a class. This is useful to validate inputs against classes that are exported from third-party libraries.

z.instanceof

class Test {
  name: string;
}

const TestSchema = z.instanceof(Test);

const blob: any = "whatever";
TestSchema.parse(new Test()); // passes
TestSchema.parse("blob"); // throws

Functions

Zod also lets you define "function schemas". This makes it easy to validate the inputs and outputs of a function without intermixing your validation code and "business logic".

You can create a function schema with .

z.function(args, returnType)

const myFunction = z.function();

type myFunction = z.infer<typeof myFunction>;
// => ()=>unknown

Define inputs and outputs.

const myFunction = z
  .function()
  .args(z.string(), z.number()) // accepts an arbitrary number of arguments
  .returns(z.boolean());

type myFunction = z.infer<typeof myFunction>;
// => (arg0: string, arg1: number)=>boolean

Function schemas have an method which accepts a function and returns a new function that automatically validates its inputs and outputs.

.implement()

const trimmedLength = z
  .function()
  .args(z.string()) // accepts an arbitrary number of arguments
  .returns(z.number())
  .implement((x) => {
    // TypeScript knows x is a string!
    return x.trim().length;
  });

trimmedLength("sandwich"); // => 8
trimmedLength(" asdf "); // => 4

If you only care about validating inputs, just don't call the method. The output type will be inferred from the implementation.

.returns()

You can use the special option if your function doesn't return anything. This will let Zod properly infer the type of void-returning functions. (Void-returning functions actually return undefined.)

z.void()

const myFunction = z
  .function()
  .args(z.string())
  .implement((arg) => {
    return [arg.length];
  });

myFunction; // (arg: string)=>number[]

Extract the input and output schemas from a function schema.

myFunction.parameters();
// => ZodTuple<[ZodString, ZodNumber]>

myFunction.returnType();
// => ZodBoolean

Preprocess

Zod now supports primitive coercion without the need for . See the coercion docs for more information.

.preprocess()

Typically Zod operates under a "parse then transform" paradigm. Zod validates the input first, then passes it through a chain of transformation functions. (For more information about transforms, read the .transform docs.)

But sometimes you want to apply some transform to the input before parsing happens. A common use case: type coercion. Zod enables this with the .

z.preprocess()

const castToString = z.preprocess((val) => String(val), z.string());

This returns a instance. is a wrapper class that contains all logic pertaining to preprocessing, refinements, and transforms.

ZodEffects
ZodEffects

Custom schemas

You can create a Zod schema for any TypeScript type by using . This is useful for creating schemas for types that are not supported by Zod out of the box, such as template string literals.

z.custom()

const px = z.custom<`${number}px`>((val) => /^\d+px$/.test(val));
px.parse("100px"); // pass
px.parse("100vw"); // fail

If you don't provide a validation function, Zod will allow any value. This can be dangerous!

z.custom<{ arg: string }>(); // performs no validation

Schema methods

All Zod schemas contain certain methods.

.parse

.parse(data: unknown): T

Given any Zod schema, you can call its method to check is valid. If it is, a value is returned with full type information! Otherwise, an error is thrown.

.parse
data

IMPORTANT: The value returned by is a deep clone of the variable you passed in.

.parse

const stringSchema = z.string();

stringSchema.parse("fish"); // => returns "fish"
stringSchema.parse(12); // throws Error('Non-string type: number');

.parseAsync

.parseAsync(data:unknown): Promise<T>

If you use asynchronous refinements or transforms (more on those later), you'll need to use

.parseAsync

const stringSchema1 = z.string().refine(async (val) => val.length < 20);
const value1 = await stringSchema.parseAsync("hello"); // => hello

const stringSchema2 = z.string().refine(async (val) => val.length > 20);
const value2 = await stringSchema.parseAsync("hello"); // => throws

.safeParse

.safeParse(data:unknown): { success: true; data: T; } | { success: false; error: ZodError; }

If you don't want Zod to throw errors when validation fails, use . This method returns an object containing either the successfully parsed data or a ZodError instance containing detailed information about the validation problems.

.safeParse

stringSchema.safeParse(12);
// => { success: false; error: ZodError }

stringSchema.safeParse("billie");
// => { success: true; data: 'billie' }

The result is a discriminated union so you can handle errors very conveniently:

const result = stringSchema.safeParse("billie");
if (!result.success) {
  // handle error then return
  result.error;
} else {
  // do something
  result.data;
}

.safeParseAsync

Alias:

.spa

An asynchronous version of .

safeParse

await stringSchema.safeParseAsync("billie");

For convenience, this has been aliased to :

.spa

await stringSchema.spa("billie");

.refine

.refine(validator: (data:T)=>any, params?: RefineParams)

Zod lets you provide custom validation logic via refinements. (For advanced features like creating multiple issues and customizing error codes, see

.superRefine
.)

Zod was designed to mirror TypeScript as closely as possible. But there are many so-called "refinement types" you may wish to check for that can't be represented in TypeScript's type system. For instance: checking that a number is an integer or that a string is a valid email address.

For example, you can define a custom validation check on any Zod schema with :

.refine

const myString = z.string().refine((val) => val.length <= 255, {
  message: "String can't be more than 255 characters",
});

⚠️ Refinement functions should not throw. Instead they should return a falsy value to signal failure.

Arguments

As you can see, takes two arguments.

.refine

  1. The first is the validation function. This function takes one input (of type — the inferred type of the schema) and returns . Any truthy value will pass validation. (Prior to zod@1.6.2 the validation function had to return a boolean.)
    T
    any
  2. The second argument accepts some options. You can use this to customize certain error-handling behavior:
type RefineParams = {
  // override error message
  message?: string;

  // appended to error path
  path?: (string | number)[];

  // params object you can use to customize message
  // in error map
  params?: object;
};

For advanced cases, the second argument can also be a function that returns

RefineParams
/

const longString = z.string().refine(
  (val) => val.length > 10,
  (val) => ({ message: `${val} is not more than 10 characters` })
);

Customize error path

const passwordForm = z
  .object({
    password: z.string(),
    confirm: z.string(),
  })
  .refine((data) => data.password === data.confirm, {
    message: "Passwords don't match",
    path: ["confirm"], // path of error
  });

passwordForm.parse({ password: "asdf", confirm: "qwer" });

Because you provided a parameter, the resulting error will be:

path

ZodError {
  issues: [{
    "code": "custom",
    "path": [ "confirm" ],
    "message": "Passwords don't match"
  }]
}

Asynchronous refinements

Refinements can also be async:

const userId = z.string().refine(async (id) => {
  // verify that ID exists in database
  return true;
});

⚠️ If you use async refinements, you must use the method to parse data! Otherwise Zod will throw an error.

.parseAsync

Relationship to transforms

Transforms and refinements can be interleaved:

z.string()
  .transform((val) => val.length)
  .refine((val) => val > 25);

.superRefine

The method is actually syntactic sugar atop a more versatile (and verbose) method called . Here's an example:

.refine
superRefine

const Strings = z.array(z.string()).superRefine((val, ctx) => {
  if (val.length > 3) {
    ctx.addIssue({
      code: z.ZodIssueCode.too_big,
      maximum: 3,
      type: "array",
      inclusive: true,
      message: "Too many items 😡",
    });
  }

  if (val.length !== new Set(val).size) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: `No duplicates allowed.`,
    });
  }
});

You can add as many issues as you like. If is not called during the execution of the function, validation passes.

ctx.addIssue

Normally refinements always create issues with a error code, but with you can create any issue of any code. Each issue code is described in detail in the Error Handling guide: ERROR_HANDLING.md.

ZodIssueCode.custom
superRefine

Abort early

By default, parsing will continue even after a refinement check fails. For instance, if you chain together multiple refinements, they will all be executed. However, it may be desirable to abort early to prevent later refinements from being executed. To achieve this, pass the flag to and return .

fatal
ctx.addIssue
z.NEVER

const schema = z.number().superRefine((val, ctx) => {
  if (val < 10) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "should be >= 10",
      fatal: true,
    });

    return z.NEVER;
  }

  if (val !== 12) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "should be twelve",
    });
  }
});

Type refinements

If you provide a type predicate to or , the resulting type will be narrowed down to your predicate's type. This is useful if you are mixing multiple chained refinements and transformations:

.refine()
superRefine()

const schema = z
  .object({
    first: z.string(),
    second: z.number(),
  })
  .nullable()
  .superRefine((arg, ctx): arg is { first: string; second: number } => {
    if (!arg) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom, // customize your issue
        message: "object should exist",
      });
      return false;
    }
    return true;
  })
  // here, TS knows that arg is not null
  .refine((arg) => arg.first === "bob", "`first` is not `bob`!");

⚠️ You must still call if using with a type predicate function. Otherwise the refinement won't be validated.

ctx.addIssue()
superRefine()

.transform

To transform data after parsing, use the method.

transform

const stringToNumber = z.string().transform((val) => val.length);

stringToNumber.parse("string"); // => 6

Chaining order

Note that above is an instance of the subclass. It is NOT an instance of . If you want to use the built-in methods of (e.g. ) you must apply those methods before any transforms.

stringToNumber
ZodEffects
ZodString
ZodString
.email()

const emailToDomain = z
  .string()
  .email()
  .transform((val) => val.split("@")[1]);

emailToDomain.parse("colinhacks@example.com"); // => example.com

Validating during transform

The method can simultaneously validate and transform the value. This is often simpler and less duplicative than chaining and .

.transform
refine
validate

As with , the transform function receives a object with a method that can be used to register validation issues.

.superRefine
ctx
addIssue

const Strings = z.string().transform((val, ctx) => {
  const parsed = parseInt(val);
  if (isNaN(parsed)) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      message: "Not a number",
    });

    // This is a special symbol you can use to
    // return early from the transform function.
    // It has type `never` so it does not affect the
    // inferred return type.
    return z.NEVER;
  }
  return parsed;
});

Relationship to refinements

Transforms and refinements can be interleaved. These will be executed in the order they are declared.

const nameToGreeting = z
  .string()
  .transform((val) => val.toUpperCase())
  .refine((val) => val.length > 15)
  .transform((val) => `Hello ${val}`)
  .refine((val) => val.indexOf("!") === -1);

Async transforms

Transforms can also be async.

const IdToUser = z
  .string()
  .uuid()
  .transform(async (id) => {
    return await getUserById(id);
  });

⚠️ If your schema contains asynchronous transforms, you must use .parseAsync() or .safeParseAsync() to parse data. Otherwise Zod will throw an error.

.default

You can use transforms to implement the concept of "default values" in Zod.

const stringWithDefault = z.string().default("tuna");

stringWithDefault.parse(undefined); // => "tuna"

Optionally, you can pass a function into that will be re-executed whenever a default value needs to be generated:

.default

const numberWithRandomDefault = z.number().default(Math.random);

numberWithRandomDefault.parse(undefined); // => 0.4413456736055323
numberWithRandomDefault.parse(undefined); // => 0.1871840107401901
numberWithRandomDefault.parse(undefined); // => 0.7223408162401552

Conceptually, this is how Zod processes default values:

  1. If the input is , the default value is returned
    undefined
  2. Otherwise, the data is parsed using the base schema

.catch

Use to provide a "catch value" to be returned in the event of a parsing error.

.catch()

const numberWithCatch = z.number().catch(42);

numberWithCatch.parse(5); // => 5
numberWithCatch.parse("tuna"); // => 42

Optionally, you can pass a function into that will be re-executed whenever a default value needs to be generated:

.catch

const numberWithRandomCatch = z.number().catch(Math.random);

numberWithRandomDefault.parse("sup"); // => 0.4413456736055323
numberWithRandomDefault.parse("sup"); // => 0.1871840107401901
numberWithRandomDefault.parse("sup"); // => 0.7223408162401552

Conceptually, this is how Zod processes "catch values":

  1. The data is parsed using the base schema
  2. If the parsing fails, the "catch value" is returned

.optional

A convenience method that returns an optional version of a schema.

const optionalString = z.string().optional(); // string | undefined

// equivalent to
z.optional(z.string());

.nullable

A convenience method that returns a nullable version of a schema.

const nullableString = z.string().nullable(); // string | null

// equivalent to
z.nullable(z.string());

.nullish

A convenience method that returns a "nullish" version of a schema. Nullish schemas will accept both and . Read more about the concept of "nullish" in the TypeScript 3.7 release notes.

undefined
null

const nullishString = z.string().nullish(); // string | null | undefined

// equivalent to
z.string().optional().nullable();

.array

A convenience method that returns an array schema for the given type:

const stringArray = z.string().array(); // string[]

// equivalent to
z.array(z.string());

.promise

A convenience method for promise types:

const stringPromise = z.string().promise(); // Promise<string>

// equivalent to
z.promise(z.string());

.or

A convenience method for union types.

const stringOrNumber = z.string().or(z.number()); // string | number

// equivalent to
z.union([z.string(), z.number()]);

.and

A convenience method for creating intersection types.

const nameAndAge = z
  .object({ name: z.string() })
  .and(z.object({ age: z.number() })); // { name: string } & { age: number }

// equivalent to
z.intersection(z.object({ name: z.string() }), z.object({ age: z.number() }));

.brand

.brand<T>() => ZodBranded<this, B>

TypeScript's type system is structural, which means that any two types that are structurally equivalent are considered the same.

type Cat = { name: string };
type Dog = { name: string };

const petCat = (cat: Cat) => {};
const fido: Dog = { name: "fido" };
petCat(fido); // works fine

In some cases, its can be desirable to simulate nominal typing inside TypeScript. For instance, you may wish to write a function that only accepts an input that has been validated by Zod. This can be achieved with branded types (AKA opaque types).

const Cat = z.object({ name: z.string() }).brand<"Cat">();
type Cat = z.infer<typeof Cat>;

const petCat = (cat: Cat) => {};

// this works
const simba = Cat.parse({ name: "simba" });
petCat(simba);

// this doesn't
petCat({ name: "fido" });

Under the hood, this works by attaching a "brand" to the inferred type using an intersection type. This way, plain/unbranded data structures are no longer assignable to the inferred type of the schema.

const Cat = z.object({ name: z.string() }).brand<"Cat">();
type Cat = z.infer<typeof Cat>;
// {name: string} & {[symbol]: "Cat"}

Note that branded types do not affect the runtime result of . It is a static-only construct.

.parse

Guides and concepts

Type inference

You can extract the TypeScript type of any schema with .

z.infer<typeof mySchema>

const A = z.string();
type A = z.infer<typeof A>; // string

const u: A = 12; // TypeError
const u: A = "asdf"; // compiles

What about transforms?

In reality each Zod schema internally tracks two types: an input and an output. For most schemas (e.g. ) these two are the same. But once you add transforms into the mix, these two values can diverge. For instance has an input of and an output of .

z.string()
z.string().transform(val => val.length)
string
number

You can separately extract the input and output types like so:

const stringToNumber = z.string().transform((val) => val.length);

// ⚠️ Important: z.infer returns the OUTPUT type!
type input = z.input<typeof stringToNumber>; // string
type output = z.output<typeof stringToNumber>; // number

// equivalent to z.output!
type inferred = z.infer<typeof stringToNumber>; // number

Writing generic functions

When attempting to write a function that accepts a Zod schema as an input, it's common to try something like this:

function makeSchemaOptional<T>(schema: z.ZodType<T>) {
  return schema.optional();
}

This approach has some issues. The variable in this function is typed as an instance of , which is an abstract class that all Zod schemas inherit from. This approach loses type information, namely which subclass the input actually is.

schema
ZodType

const arg = makeSchemaOptional(z.string());
arg.unwrap();

A better approach is for the generic parameter to refer to the schema as a whole.

function makeSchemaOptional<T extends z.ZodTypeAny>(schema: T) {
  return schema.optional();
}

ZodTypeAny
is just a shorthand for , a type that is broad enough to match any Zod schema.
ZodType<any, any, any>

As you can see, is now fully and properly typed.

schema

const arg = makeSchemaOptional(z.string());
arg.unwrap(); // ZodString

Constraining allowable inputs

The class has three generic parameters.

ZodType

class ZodType<
  Output = any,
  Def extends ZodTypeDef = ZodTypeDef,
  Input = Output
> { ... }

By constraining these in your generic input, you can limit what schemas are allowable as inputs to your function:

function makeSchemaOptional<T extends z.ZodType<string>>(schema: T) {
  return schema.optional();
}

makeSchemaOptional(z.string());
// works fine

makeSchemaOptional(z.number());
// Error: 'ZodNumber' is not assignable to parameter of type 'ZodType<string, ZodTypeDef, string>'

Error handling

Zod provides a subclass of Error called . ZodErrors contain an array containing detailed information about the validation problems.

ZodError
issues

const data = z
  .object({
    name: z.string(),
  })
  .safeParse({ name: 12 });

if (!data.success) {
  data.error.issues;
  /* [
      {
        "code": "invalid_type",
        "expected": "string",
        "received": "number",
        "path": [ "name" ],
        "message": "Expected string, received number"
      }
  ] */
}

For detailed information about the possible error codes and how to customize error messages, check out the dedicated error handling guide: ERROR_HANDLING.md

Zod's error reporting emphasizes completeness and correctness. If you are looking to present a useful error message to the end user, you should either override Zod's error messages using an error map (described in detail in the Error Handling guide) or use a third party library like

zod-validation-error

Error formatting

You can use the method to convert this error into a nested object.

.format()

const data = z
  .object({
    name: z.string(),
  })
  .safeParse({ name: 12 });

if (!data.success) {
  const formatted = data.error.format();
  /* {
    name: { _errors: [ 'Expected string, received number' ] }
  } */

  formatted.name?._errors;
  // => ["Expected string, received number"]
}

Comparison

There are a handful of other widely-used validation libraries, but all of them have certain design limitations that make for a non-ideal developer experience.

Joi

https://github.com/hapijs/joi

Doesn't support static type inference 😕

Yup

https://github.com/jquense/yup

Yup is a full-featured library that was implemented first in vanilla JS, and later rewritten in TypeScript.

  • Supports casting and transforms
  • All object fields are optional by default
  • Missing object methods: (partial, deepPartial)
  • Missing promise schemas
  • Missing function schemas
  • Missing union & intersection schemas

io-ts

https://github.com/gcanti/io-ts

io-ts is an excellent library by gcanti. The API of io-ts heavily inspired the design of Zod.

In our experience, io-ts prioritizes functional programming purity over developer experience in many cases. This is a valid and admirable design goal, but it makes io-ts particularly hard to integrate into an existing codebase with a more procedural or object-oriented bias. For instance, consider how to define an object with optional properties in io-ts:

import * as t from "io-ts";

const A = t.type({
  foo: t.string,
});

const B = t.partial({
  bar: t.number,
});

const C = t.intersection([A, B]);

type C = t.TypeOf<typeof C>;
// returns { foo: string; bar?: number | undefined }

You must define the required and optional props in separate object validators, pass the optionals through (which marks all properties as optional), then combine them with .

t.partial
t.intersection

Consider the equivalent in Zod:

const C = z.object({
  foo: z.string(),
  bar: z.number().optional(),
});

type C = z.infer<typeof C>;
// returns { foo: string; bar?: number | undefined }

This more declarative API makes schema definitions vastly more concise.

io-ts
also requires the use of gcanti's functional programming library to parse results and handle errors. This is another fantastic resource for developers looking to keep their codebase strictly functional. But depending on necessarily comes with a lot of intellectual overhead; a developer has to be familiar with functional programming concepts and the nomenclature to use the library.
fp-ts
fp-ts
fp-ts

  • Supports codecs with serialization & deserialization transforms
  • Supports branded types
  • Supports advanced functional programming, higher-kinded types, compatibility
    fp-ts
  • Missing object methods: (pick, omit, partial, deepPartial, merge, extend)
  • Missing nonempty arrays with proper typing (
    [T, ...T[]]
    )
  • Missing promise schemas
  • Missing function schemas

Runtypes

https://github.com/pelotom/runtypes

型推論のサポートは良好ですが、オブジェクト型のマスキングのオプションが制限されています (、などはありません)。sはサポートされていません(それらはZodと同等です)。それらはブランド化された型と読み取り専用型をサポートしていますが、Zodはサポートしていません。

.pick
.omit
.extend
Record
Record
object

  • 「パターンマッチング」をサポート:共用体に分散する計算プロパティ
  • 読み取り専用型をサポート
  • 欠落しているオブジェクトメソッド:(ディープパーシャル、マージ)
  • 適切な型指定で空でない配列がありません (
    [T, ...T[]]
    )
  • 約束スキーマの欠落
  • エラーのカスタマイズがありません

おお

https://github.com/sindresorhus/ow

Owは関数入力の検証に重点を置いています。これは、複雑なアサートステートメントを簡単に表現できるライブラリですが、型指定されていないデータを解析することはできません。それらははるかに多様なタイプをサポートしています。Zod は TypeScript の型システムとほぼ 1 対 1 のマッピングを持っていますが、ow ではいくつかの非常に特殊な型をすぐに検証できます (例: 、彼らのREADMEの完全なリストを参照してください)。

int32Array

関数の入力を検証する場合は、Zod の関数スキーマを使用してください。これは、関数型宣言を繰り返すことなく再利用できる、はるかに単純なアプローチです(つまり、すべての関数の先頭に一連のowアサーションをコピーして貼り付けます)。また、Zodでは戻り値の型も検証できるため、ダウンストリームに渡される予期しないデータがないことを確認できます。

変更履歴

CHANGELOG.md で変更ログを見る