LoginSignup
2
0

Zod入門

Last updated at Posted at 2024-03-20

Zod

  • TypeScriptで使える、データ構造をチェックするライブラリ
  • バリデーションをするのによい

スキーマ

  • データ構造の定義
const mySchema = z.string();

const User = z.object({
  username: z.string(),
});
// (小文字objectはプリミティブ型以外の型)

パース

  • データ構造に合うかをチェック
// スキーマ.parse(チェックしたい対象)の形式
mySchema.parse("tuna") // =>"tuna"
mySchema.parse(12) //=>throws ZodError
User.parse({ username: "Ludwig" });

// safeParseを使うと、エラースローされない
mySchema.safeParse("tuna"); // => { success: true; data: "tuna" }
mySchema.safeParse(12); // => { success: false; error: ZodError }

coercion

  • 型の変換を行う
  • 変換できない場合はエラー
  • 内部的にはJavaScriptのString()メソッドで変換が行われる
const schema = z.coerce.string();
schema.parse("tuna") //=> "tuna"
schema.parse("12") //=> "12"

エラーメッセージ

  • stringなどのスキーマでは、エラーメッセージを設定できる
const FormSchema = z.object({
  id: z.string(),
  customerId: z.string({
    invalid_type_error: 'Please select a customer.',
  }),
  status: z.enum(['pending', 'paid'], {
    invalid_type_error: 'Please select an invoice status.',
  })
});

参考:

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