9148c358d0
Topic_Agent/Topic_Blog/Topics/Topics_Biz/Topics_Meeting/Topics_Rag의 마크다운 지식 문서를 Topic_General/Topic_Programming/Topic_Graphic/Topic_Business 4개 카테고리로 재분류. - 중복 제거: frontmatter의 status:duplicate/merged + duplicate_of/redirect_to 필드로 자기 자신을 중복으로 선언한 리다이렉트 stub 1032개 제거, 완전 동일 내용 파일 472개 제거, 동일 파일명·다른 내용 충돌 시 더 큰(완전한) 버전만 유지(162개 제거) — 총 1639개 중복 제거. - 분류: 폴더 단위로 명확한 항목(AI_and_ML/Coding/Architecture 등 → Programming, Comfyui/Visual_Effects → Graphic, Topics_Biz/Topics_Meeting/사업 등 → Business, Poetic_Blog_Writing/창의성/Game_Design 등 → General)은 폴더 우선순위로, 나머지 혼재 폴더(Topic_Agent/Topic_Blog/Topics 루트/Thinking & Reasoning/Other/UI_UX_Assets)는 title/tags 키워드 스코어링으로 파일 단위 분류(불명확한 경우 General로 폴백). 원본 폴더명은 "From_*" 서브폴더로 보존해 추적 가능성 유지. - 최종 배치: Programming 2784 / General 1608 / Graphic 285 / Business 249 = 4926개 문서. - 에이전트 운영 상태(.astra/.agent/.obsidian/sessions/memory/_company/docs/lessons/_shared/src)는 지식 콘텐츠가 아니므로 재분류 대상에서 제외하고 원위치 유지. - Topics/Topic_email(상위 보호 폴더 Topic_email과 파일명 100% 중복) 삭제 — 보호 폴더 자체는 미변경. - 완전히 비게 된 Topic_Agent/Topic_Blog/Topics_Biz/Topics_Rag 폴더 제거.
193 lines
5.9 KiB
Markdown
193 lines
5.9 KiB
Markdown
---
|
|
id: wiki-2026-0508-zod
|
|
title: Zod
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [Zod Schema, Zod 4, ts-schema-validation]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.9
|
|
verification_status: applied
|
|
tags: [typescript, validation, schema, runtime-types]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: typescript
|
|
framework: zod
|
|
---
|
|
|
|
# Zod
|
|
|
|
## 매 한 줄
|
|
> **"매 schema 한 번 정의 매 runtime validation + static type 매 동시"**. 매 Colin McDonnell 매 2020 출시 매 TypeScript-first schema validator — 매 2026 매 Zod 4 매 stable, tRPC / OpenAI SDK / Vercel AI SDK / Next.js Server Actions 매 사실상 standard. 매 대안: Valibot (smaller bundle), ArkType (faster).
|
|
|
|
## 매 핵심
|
|
|
|
### 매 핵심 idea
|
|
- 매 single source of truth: schema 의 의 매 type 도 (`z.infer<>`) 도 의 의.
|
|
- 매 parse → validated value (typed); failure → `ZodError` (or `safeParse` returns Result-like).
|
|
- Tree-shakeable, zero deps.
|
|
|
|
### 매 주요 method
|
|
- `z.object`, `z.array`, `z.union`, `z.discriminatedUnion`, `z.record`, `z.tuple`.
|
|
- `.refine`, `.transform`, `.pipe`, `.brand`.
|
|
- `.optional`, `.nullable`, `.nullish`, `.default`, `.catch`.
|
|
- `z.infer<typeof schema>`, `z.input`, `z.output`.
|
|
|
|
### 매 응용
|
|
1. tRPC: input/output schema → end-to-end type safety.
|
|
2. React Hook Form + `zodResolver`.
|
|
3. OpenAI structured outputs / function calling: schema → JSON Schema.
|
|
4. Server Actions / API route input validation.
|
|
5. Env variable validation (zod-env, t3-env).
|
|
|
|
## 💻 패턴
|
|
|
|
### Basic schema + infer
|
|
```ts
|
|
import { z } from "zod";
|
|
|
|
const User = z.object({
|
|
id: z.string().uuid(),
|
|
email: z.string().email(),
|
|
age: z.number().int().min(0).max(150),
|
|
role: z.enum(["admin", "user", "guest"]),
|
|
});
|
|
type User = z.infer<typeof User>;
|
|
|
|
const result = User.safeParse(input);
|
|
if (!result.success) console.error(result.error.flatten());
|
|
else console.log(result.data); // typed
|
|
```
|
|
|
|
### Discriminated union
|
|
```ts
|
|
const Event = z.discriminatedUnion("type", [
|
|
z.object({ type: z.literal("click"), x: z.number(), y: z.number() }),
|
|
z.object({ type: z.literal("keydown"), key: z.string() }),
|
|
z.object({ type: z.literal("scroll"), delta: z.number() }),
|
|
]);
|
|
type Event = z.infer<typeof Event>; // narrow 매 자동
|
|
```
|
|
|
|
### Refine + transform + pipe
|
|
```ts
|
|
const Password = z.string()
|
|
.min(8)
|
|
.refine((s) => /[A-Z]/.test(s) && /\d/.test(s), "Need uppercase + digit");
|
|
|
|
const TrimmedEmail = z.string()
|
|
.transform((s) => s.trim().toLowerCase())
|
|
.pipe(z.string().email());
|
|
```
|
|
|
|
### Recursive schema (Zod 4)
|
|
```ts
|
|
type Comment = { text: string; replies: Comment[] };
|
|
const Comment: z.ZodType<Comment> = z.lazy(() =>
|
|
z.object({ text: z.string(), replies: z.array(Comment) }),
|
|
);
|
|
```
|
|
|
|
### Branded types (nominal)
|
|
```ts
|
|
const UserId = z.string().uuid().brand<"UserId">();
|
|
type UserId = z.infer<typeof UserId>;
|
|
function loadUser(id: UserId) { /* … */ }
|
|
loadUser(crypto.randomUUID() as any); // 매 must parse 먼저
|
|
```
|
|
|
|
### Form integration (React Hook Form)
|
|
```tsx
|
|
import { useForm } from "react-hook-form";
|
|
import { zodResolver } from "@hookform/resolvers/zod";
|
|
|
|
const Schema = z.object({ email: z.string().email(), age: z.coerce.number().min(18) });
|
|
type Form = z.infer<typeof Schema>;
|
|
|
|
function SignUp() {
|
|
const { register, handleSubmit, formState: { errors } } = useForm<Form>({
|
|
resolver: zodResolver(Schema),
|
|
});
|
|
return (
|
|
<form onSubmit={handleSubmit((d) => console.log(d))}>
|
|
<input {...register("email")} />
|
|
{errors.email && <span>{errors.email.message}</span>}
|
|
</form>
|
|
);
|
|
}
|
|
```
|
|
|
|
### Env validation
|
|
```ts
|
|
// env.ts — process.env 매 typed
|
|
import { z } from "zod";
|
|
|
|
export const env = z.object({
|
|
NODE_ENV: z.enum(["development", "production", "test"]),
|
|
DATABASE_URL: z.string().url(),
|
|
OPENAI_API_KEY: z.string().startsWith("sk-"),
|
|
PORT: z.coerce.number().default(3000),
|
|
}).parse(process.env);
|
|
```
|
|
|
|
### LLM structured output
|
|
```ts
|
|
import OpenAI from "openai";
|
|
import { zodResponseFormat } from "openai/helpers/zod";
|
|
|
|
const Recipe = z.object({
|
|
name: z.string(),
|
|
ingredients: z.array(z.object({ item: z.string(), qty: z.string() })),
|
|
steps: z.array(z.string()),
|
|
});
|
|
const openai = new OpenAI();
|
|
const r = await openai.chat.completions.parse({
|
|
model: "gpt-5",
|
|
messages: [{ role: "user", content: "Recipe for cacio e pepe" }],
|
|
response_format: zodResponseFormat(Recipe, "recipe"),
|
|
});
|
|
const recipe = r.choices[0].message.parsed!; // typed
|
|
```
|
|
|
|
## 매 결정 기준
|
|
| 상황 | Approach |
|
|
|---|---|
|
|
| TS-only project | Zod (default) |
|
|
| Bundle size critical (<5KB) | Valibot |
|
|
| Performance critical (10M validations/s) | ArkType |
|
|
| JSON Schema 의 매 first-class | TypeBox |
|
|
| Java / Python interop schema | JSON Schema + ajv / pydantic |
|
|
|
|
**기본값**: Zod 4. 매 모든 boundary (network, env, storage) 매 parse.
|
|
|
|
## 🔗 Graph
|
|
- 부모: [[Schema Validation]]
|
|
- 변형: [[Valibot]] · [[ArkType]] · [[Yup]]
|
|
- 응용: [[React Hook Form]] · [[Server Actions]]
|
|
- Adjacent: [[TypeScript]] · [[Branded Types]] · [[JSON Schema]]
|
|
|
|
## 🤖 LLM 활용
|
|
**언제**: API boundary parsing, env validation, LLM output parsing, form schema.
|
|
**언제 X**: Hot path (>1M ops/s) 매 ArkType 고려, embedded / no TS.
|
|
|
|
## ❌ 안티패턴
|
|
- **Inferring on `.parse` not on schema**: `z.infer<typeof S>` 매 사용.
|
|
- **`any` cast 후 parse skip**: 매 boundary 매 항상 parse.
|
|
- **Massive nested `.refine` chains**: 매 readability — `.pipe` 분리.
|
|
- **Re-parsing same data multiple times**: 매 once at boundary, 매 그 후 typed.
|
|
- **Throwing in nested transforms**: `z.NEVER` + ctx.addIssue 사용.
|
|
- **Optional vs nullable 혼동**: optional = `| undefined`, nullable = `| null`.
|
|
|
|
## 🧪 검증 / 중복
|
|
- Verified (Zod 4 official docs, colinhacks/zod GitHub, tRPC/Vercel AI SDK integration).
|
|
- 신뢰도 A.
|
|
|
|
## 🕓 Changelog
|
|
| 날짜 | 변경 |
|
|
|---|---|
|
|
| 2026-05-08 | Phase 1 |
|
|
| 2026-05-10 | Manual cleanup — Zod 4, schema patterns, LLM structured output integration |
|