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?

【TypeScript】zod4でobjectのparse時に不要な値を処理する時の対応

0
Posted at

概要

3-4. 不要な値があったときに除外したい (strict / strip )、3-5. 不要な値があったときに素通ししたい ( passsthrough / catchall)の記事で紹介されている通り、zodではobjectのparse時に不要な値を処理するための関数が用意されています。
zod4では関数がdeprecatedになるなどの変更があり、不要な値処理の関数もdeprecatedになって新しい関数が用意されていたりします。zod4のMigration guideに変更点は記載ありますが、今回はその動作を確認してみたのでメモ書きとして残しておきます。

前提

  • 使用したzodのバージョンは4.6.7です。

詳細

不要な値を削除する

動作はzod4で変更はありません。特に指定なくobjectをparseした場合は、不要な値を削除します。なお、このデフォルトの動作を指定するstripは、zod4ではdeprecatedになりました。

import { z } from "zod";

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

// emailとcustomFieldは削除される。
const resultDefault = userSchemaDefault.parse({
  id: "user-001",
  name: "Taro",
  age: 25,
  email: "taro@example.com",
  customField: "追加データ",
});
console.log(resultDefault);

不要な値を残す

looseObjectを使用しスキーマを定義します。passsthroughはzod4ではdeprecatedとなりました。

import { z } from "zod";

const userSchemaLoose = z.looseObject({
  id: z.string(),
  name: z.string(),
  age: z.number(),
});

// emailとcustomFieldは残る。
const resultLoose = userSchemaLoose.parse({
  id: "user-001",
  name: "Taro",
  age: 25,
  email: "taro@example.com",
  customField: "追加データ",
});
console.log(resultLoose);

不要な値が入った時にエラーとする

strictObjectを使用しスキーマを定義します。strictはzod4ではdeprecatedとなりました。

import { z } from "zod";

const userSchemaStrict = z.strictObject({
  id: z.string(),
  name: z.string(),
  age: z.number(),
});

// ZodError(unrecognized_keys)が起きる。
const resultStrict = userSchemaStrict.parse({
  id: "user-001",
  name: "Taro",
  age: 25,
  email: "taro@example.com",
  customField: "追加データ",
});
console.log(resultStrict);
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?