Backend2025년 4월 3일1분 읽기

Zod — 런타임 스키마 검증의 표준

YS
YoungSam
조회 1989

왜 Zod인가

TypeScript의 타입은 컴파일 타임에만 존재합니다. 런타임에서 API 응답, 폼 데이터 등을 검증하려면 Zod가 필요합니다.

스키마 정의

import { z } from "zod";

const UserSchema = z.object({
  name: z.string().min(2).max(50),
  email: z.string().email(),
  age: z.number().int().positive().optional(),
  role: z.enum(["admin", "user", "editor"]),
});

type User = z.infer<typeof UserSchema>;

// 검증
const result = UserSchema.safeParse(input);
if (result.success) { /* result.data는 User 타입 */ }

tRPC, React Hook Form과 통합하면 엔드투엔드 검증이 완성됩니다.

ZodValidationTypeScript

댓글 0

아직 댓글이 없습니다.