1
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(v4)の基本的な使い方

1
Last updated at Posted at 2026-01-31

Zod(v4)を使い始めるにあたって、基本的な使い方を自分用としてまとめる。

基本的なスキーマ定義

プリミティブ型のスキーマは以下。

import * as z from 'zod';

z.string(); // String
z.number(); // Number
z.bigint(); // BigInt
z.boolean(); // Boolean
z.symbol(); // Symbol
z.undefined(); // undefined
z.null(); // null

文字列のバリデーション

import * as z from 'zod';

z.string().max(5);
z.string().min(5);
z.string().length(5);

フォーマットも指定できる。

import * as z from 'zod';

z.email(); // Email形式
z.url(); // URL形式
// 他にも色々ある

オブジェクトスキーマ

import * as z from 'zod';

z.object({
  id: z.number(),
  name: z.string(),
});

配列スキーマ

import * as z from 'zod';

z.array(z.string());

配列のバリデーションも可能。

import * as z from 'zod';

z.array(z.string()).min(5);
z.array(z.string()).max(5);
z.array(z.string()).length(5);

バリデーションの実行

.parse().safeParse()の2つの方法がある。

.parse()は、バリデーションに失敗すると例外をスローする。

import * as z from 'zod';

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});

userSchema.parse({ id: 1, name: 'Taro' }); // { id: 1, name: 'Taro' } が返る
userSchema.parse({ id: '1', name: 'Taro' }); // ZodErrorをThrow

.safeParse()は、例外をスローせず結果をオブジェクトで返す。

import * as z from 'zod';

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});

const successResult = userSchema.safeParse({ id: 1, name: 'Taro' });
// { success: true, data: { id: 1, name: 'Taro' } }

const failResult = userSchema.safeParse({ id: '1', name: 'Taro' });
// { success: false, error: ZodError }

型の推論

z.inferを使うと、スキーマからTypeScriptの型を推論できる。

import * as z from 'zod';

const userSchema = z.object({
  id: z.number(),
  name: z.string(),
});

type User = z.infer<typeof userSchema>;
// { id: number; name: string; }

const user: User = {
  id: 1,
  name: 'Taro',
};
1
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
1
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?