Zod?
💡스키마 선언 및 유효성 검사 라이브러리
🤔 Zod가 필요한 이유는 무엇일까
TypeScript의 한계 때문이다.
TypeScript는 컴파일 시점에서만 타입에러를 잡아낼 수 있다.
➡️ 즉, 런타임 단계에서의 타입 에러는 잡을 수가 없다.
또한 TypeScript는 문자열이나 원하는 숫자 범위를 강제하거나 number타입을 더욱 구체적으로 정수나 실수로의 구분이 불가능하다.
설치
pnpm add zod # pnpm
- TypeScript 4.5 이상가능
- tsconfig.json 에 "strict": true 설정이 되어있어야 한다.
사용
//문자열만 허용
const Schema1 = z.string();
// 문자열이 있으면 4~20까지 허용, optional일 경우 undefined도 허용
const Schema2 = z.string().min(4).max(20).optional();
coerce
타입이 맞지 않더라도 타입을 강제 변환 시켜준다.
const shema = z.coerce.string();
shema.parse("tuna");
shema.parse(12); // => "tuna" 숫자가 오더라도 강제로 타입을 변환 시켜준다.
default
const Schema1 = z.string().default("tuna")
Schema1.parse(undefined) // => "tuna"
catch
const Schema1 = z.string().cath("42")
Schema1.parse(5) // => "42" 오류가 발생했을 경우 "42"
.or .and
// .or .union
const Schema1 = z.string().or(z.number()) // string | number
z.union([z.string(), z.number()])
// .and .intersection
const Schema2 = z.object({name:z.string()}).and(z.object({age:z.number() }))
z.intersection(z.object({name:z.string() }), z.object({ age : z.number() }));
에러에 대한 메세지
const name = z.string({ message: 'string error' });
이보다 유용한 메서드 들이 매우 많다. 그건 아래의 공식 문서를 참고하는 것이 좋을 것 같다👍
💡 i18n을 사용하여 다국어 처리하기
https://github.com/aiji42/zod-i18n
GitHub - aiji42/zod-i18n: Useful for translating zod error messages.
Useful for translating zod error messages. Contribute to aiji42/zod-i18n development by creating an account on GitHub.
github.com
i18n-zod.ts
import i18next from "i18next";
import { z } from "zod";
import { zodI18nMap } from "zod-i18n-map";
import translation from "zod-i18n-map/locales/ko/zod.json";
i18next.init({
lng:'ko',
resources: {
ko:{ zod: translation },
},
});
z.setErrorMap(zodI18nMap);
export { z };

'TypeScript' 카테고리의 다른 글
| Type Challenges :00003-medium-omit (0) | 2025.05.06 |
|---|---|
| 친해지기3-Type Challenges : 00011-easy-tuple-to-object (0) | 2025.04.30 |
| 친해지기2-Type Challenges : 00007-easy-readonly (1) | 2025.04.29 |
| 친해지기1- Type Challenges : 00004-easy-pick (0) | 2025.04.28 |
| [TS] 타입 가드 & 타입 내로잉(is, as const, keyof, typeof, as) (0) | 2025.04.23 |