0
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?

【React】Zod で特定のカラムを抽出する方法

Posted at

はじめに

こんにちは。アメリカ在住で独学エンジニアを目指している Taira です。

Zod を使ってスキーマを定義していると、
「特定のカラムだけ欲しい!」とか「このキー以外いらない!」
というケース、よくありませんか?

TypeScript では以前紹介した pickomit がありますが、Zod も同様に pickomit を使うことで、簡単に実現できます。
ただし、少しだけ使い方が違うので、使い方を解説していきます


基本のスキーマ例

まずはベースとなるスキーマを用意します。

import { z } from 'zod';

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

pick : 欲しいカラムだけ抜き出す

特定のキーだけ抽出したいときは pick

const studentNameSchema = studentSchema.pick({ name: true });

type StudentName = z.infer<typeof studentNameSchema>;
// { name: string }

複数キーを選ぶのももちろん可能です。

const studentBasicSchema = studentSchema.pick({ name: true, age: true });

type StudentBasic = z.infer<typeof studentBasicSchema>;
// { name: string; age: number }

omit : 不要なカラムを除外する

逆に「いらないカラムを除く」には omit を使います。

const studentWithoutId = studentSchema.omit({ id: true });

type StudentWithoutId = z.infer<typeof studentWithoutId>;
// { name: string; age: number; grade: number }

extend : 抽出後に加工・追加もできる

さらに抽出したスキーマを元に新しいフィールドを追加するなら extend

const studentWithFlag = studentSchema
  .pick({ name: true })
  .extend({ isActive: z.boolean() });

type StudentWithFlag = z.infer<typeof studentWithFlag>;
// { name: string; isActive: boolean }

まとめ

  • 特定カラムを抽出pick
  • 不要カラムを除外omit
  • 加工・追加extend
0
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
0
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?