Zod は TypeScript 向けのスキーマ宣言とデータ検証のためのライブラリ。 Zod を使用すると、型安全な方法でデータ構造を定義し、それに基づいてデータを検証できる。
import { z } from 'zod'
const userSchema = z.object({
name: z.string(),
age: z.number(),
tel: z.string(),
})
userSchema.parse({ name: 'hoge', age: 66, tel: 'xxx-xxxx-xxxx' })const optionalString = z.string().optional()
// string | undefined
const nullableString = z.string().nullable()
// string | null
const nullishString = z.string().nullish()
// string | null | undefinedconst userSchema = z.object({
name: z.string(),
age: z.number(),
tel: z.string(),
})
type user = z.infer<typeof userSchema>import { z } from 'zod'
// 文字列のスキーマの作成
const stringScheme = z.string()
stringScheme.parse("hoge")
// => "hoge"
stringScheme.parse(12)
// => throws ZodError検証が失敗したときにZodエラーをスローしたくない場合は、.safeParse()を使用する。
import { z } from 'zod'
const stringScheme = z.string()
stringScheme.safeParse(12);
// => { success: false; error: ZodError }
stringSchema.safeParse("hoge");
// => { success: true; data: 'hoge' }エラーメッセージをカスタマイズしたり、min や max を適用したりすることも可能。
import { z } from 'zod';
const optionalTrimmedString = z.string().trim().optional().default('');
export const postPayloadSchema = z.object({
title: z.string().trim().min(1, 'Title is required.').max(200, 'Title is too long.'),
content: z.string().trim().min(1, 'Content is required.'),
excerpt: optionalTrimmedString
.refine((value) => value.length <= 300, 'Excerpt is too long.')
.transform(normalizeNullableText),
coverImage: optionalTrimmedString
.refine(
(value) => value.length === 0 || z.url().safeParse(value).success,
'Cover image must be a valid URL.'
)
.transform(normalizeNullableText),
tags: optionalTrimmedString
.refine((value) => value.length <= 200, 'Tags are too long.')
.transform(normalizeTags),
published: z.boolean(),
});
export const postsQuerySchema = z.object({
published: z.enum(['true', 'false']).optional(),
});
export type PostPayload = z.infer<typeof postPayloadSchema>;