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 폴더 제거.
208 lines
6.2 KiB
Markdown
208 lines
6.2 KiB
Markdown
---
|
|
id: wiki-2026-0508-discriminated-unions
|
|
title: Discriminated Unions
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [Tagged Unions, Sum Types, Algebraic Data Types, ADT]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.95
|
|
verification_status: applied
|
|
tags: [typescript, types, functional, type-narrowing]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: typescript
|
|
framework: type-system
|
|
---
|
|
|
|
# Discriminated Unions
|
|
|
|
## 매 한 줄
|
|
> **"매 한 literal field 의 매 type narrow"**. 매 TS / F# / Rust enum / Haskell ADT 의 same idea — 매 union 의 each variant 의 unique discriminant (tag) 의 carry, 매 compiler 의 매 switch 시 매 narrow. 매 2026 TS 5.7 의 매 dominant data modeling pattern.
|
|
|
|
## 매 핵심
|
|
|
|
### 매 anatomy
|
|
```typescript
|
|
type Result<T, E> =
|
|
| { kind: "ok"; value: T }
|
|
| { kind: "err"; error: E };
|
|
// ^^^^^^^^^^^ 매 discriminant — 매 string / number / boolean literal.
|
|
```
|
|
|
|
### 매 narrowing rules
|
|
- 매 discriminant 의 literal 의 must.
|
|
- 매 `switch` / `if` 매 변수 의 narrow.
|
|
- 매 exhaustive check 의 `never` 의 leverage.
|
|
|
|
### 매 vs alternatives
|
|
- **vs class hierarchy**: 매 closed set, 매 pattern-match easy, 매 no `instanceof`.
|
|
- **vs enum**: 매 enum 의 variant 별 data 의 X — DU 의 carry.
|
|
- **vs untagged union**: 매 narrow 의 hard, 매 runtime check 의 brittle.
|
|
|
|
### 매 응용
|
|
1. Result / Option / Either monads.
|
|
2. State machine state.
|
|
3. Redux / xstate action / event.
|
|
4. API response variants.
|
|
5. AST node types.
|
|
|
|
## 💻 패턴
|
|
|
|
### Pattern 1: Result / Either
|
|
```typescript
|
|
type Result<T, E = Error> =
|
|
| { ok: true; value: T }
|
|
| { ok: false; error: E };
|
|
|
|
function parseJson<T>(s: string): Result<T> {
|
|
try { return { ok: true, value: JSON.parse(s) }; }
|
|
catch (e) { return { ok: false, error: e as Error }; }
|
|
}
|
|
|
|
const r = parseJson<User>(input);
|
|
if (r.ok) {
|
|
r.value.name; // 매 narrowed 의 T
|
|
} else {
|
|
r.error.message; // 매 narrowed 의 E
|
|
}
|
|
```
|
|
|
|
### Pattern 2: Exhaustive switch with `never`
|
|
```typescript
|
|
type Shape =
|
|
| { kind: "circle"; radius: number }
|
|
| { kind: "square"; side: number }
|
|
| { kind: "rectangle"; w: number; h: number };
|
|
|
|
function area(s: Shape): number {
|
|
switch (s.kind) {
|
|
case "circle": return Math.PI * s.radius ** 2;
|
|
case "square": return s.side ** 2;
|
|
case "rectangle": return s.w * s.h;
|
|
default:
|
|
const _exhaustive: never = s; // 매 새 variant 추가 시 compile error
|
|
throw new Error(`unhandled: ${_exhaustive}`);
|
|
}
|
|
}
|
|
```
|
|
|
|
### Pattern 3: State machine state
|
|
```typescript
|
|
type FetchState<T> =
|
|
| { status: "idle" }
|
|
| { status: "loading"; abortCtrl: AbortController }
|
|
| { status: "success"; data: T; fetchedAt: Date }
|
|
| { status: "error"; error: Error; retryCount: number };
|
|
|
|
function reducer<T>(s: FetchState<T>, ev: FetchEvent<T>): FetchState<T> {
|
|
if (s.status === "loading" && ev.type === "abort") {
|
|
s.abortCtrl.abort();
|
|
return { status: "idle" };
|
|
}
|
|
// ...
|
|
}
|
|
```
|
|
|
|
### Pattern 4: Redux-style action
|
|
```typescript
|
|
type TodoAction =
|
|
| { type: "ADD"; text: string }
|
|
| { type: "TOGGLE"; id: string }
|
|
| { type: "DELETE"; id: string }
|
|
| { type: "EDIT"; id: string; text: string };
|
|
|
|
function reducer(state: Todo[], action: TodoAction): Todo[] {
|
|
switch (action.type) {
|
|
case "ADD": return [...state, { id: uid(), text: action.text, done: false }];
|
|
case "TOGGLE": return state.map(t => t.id === action.id ? { ...t, done: !t.done } : t);
|
|
case "DELETE": return state.filter(t => t.id !== action.id);
|
|
case "EDIT": return state.map(t => t.id === action.id ? { ...t, text: action.text } : t);
|
|
}
|
|
}
|
|
```
|
|
|
|
### Pattern 5: API response variants
|
|
```typescript
|
|
type ApiResponse<T> =
|
|
| { status: 200; data: T }
|
|
| { status: 401; reason: "expired" | "invalid" }
|
|
| { status: 429; retryAfterSec: number }
|
|
| { status: 500; traceId: string };
|
|
|
|
async function call<T>(url: string): Promise<ApiResponse<T>> { /* ... */ }
|
|
```
|
|
|
|
### Pattern 6: Pattern-match helper (ts-pattern)
|
|
```typescript
|
|
import { match, P } from "ts-pattern";
|
|
|
|
const message = match(response)
|
|
.with({ status: 200 }, r => `Got ${r.data.length} items`)
|
|
.with({ status: 401, reason: "expired" }, () => "Please refresh token")
|
|
.with({ status: 429 }, r => `Wait ${r.retryAfterSec}s`)
|
|
.with({ status: 500 }, r => `Error ${r.traceId}`)
|
|
.exhaustive();
|
|
```
|
|
|
|
### Pattern 7: Zod parsing → DU
|
|
```typescript
|
|
import { z } from "zod";
|
|
|
|
const Event = z.discriminatedUnion("type", [
|
|
z.object({ type: z.literal("click"), x: z.number(), y: z.number() }),
|
|
z.object({ type: z.literal("key"), key: z.string() }),
|
|
z.object({ type: z.literal("scroll"), dy: z.number() }),
|
|
]);
|
|
type Event = z.infer<typeof Event>;
|
|
```
|
|
|
|
### Pattern 8: assertNever helper
|
|
```typescript
|
|
export function assertNever(x: never): never {
|
|
throw new Error(`unexpected: ${JSON.stringify(x)}`);
|
|
}
|
|
// 매 default case 의 use.
|
|
```
|
|
|
|
## 매 결정 기준
|
|
| 상황 | Approach |
|
|
|---|---|
|
|
| Closed set of variants | DU |
|
|
| Open extensible | class + interface |
|
|
| Boolean flag pair | DU (truthy combos 의 prevent) |
|
|
| Many variants (~20+) | DU + ts-pattern |
|
|
| Server boundary | Zod discriminatedUnion |
|
|
|
|
**기본값**: 매 union 의 require 시 매 DU + `kind` / `type` / `status` discriminant.
|
|
|
|
## 🔗 Graph
|
|
- 부모: [[TypeScript Type System]] · [[Algebraic Data Types]]
|
|
- 변형: [[Tagged Unions]] · [[Sum Types]]
|
|
- 응용: [[Result Type]] · [[State Machine]] · [[Zod]]
|
|
- Adjacent: [[Pattern Matching]] · [[Exhaustiveness Checking]]
|
|
|
|
## 🤖 LLM 활용
|
|
**언제**: 매 type modeling, 매 state machine, 매 API contract, 매 reducer.
|
|
**언제 X**: 매 single-variant — 매 plain interface.
|
|
|
|
## ❌ 안티패턴
|
|
- **No discriminant**: 매 untagged union — 매 narrow 의 hard.
|
|
- **String discriminant 의 typo**: 매 magic string 의 const 의 hoist.
|
|
- **Boolean flag combos**: `{loading, success, error}` boolean — 매 DU 의 use.
|
|
- **Default case 의 swallow**: `default: return state` — 매 새 variant 시 silent miss.
|
|
- **Class hierarchy 의 simulate**: 매 DU 의 cleaner.
|
|
|
|
## 🧪 검증 / 중복
|
|
- Verified (TS handbook "Narrowing", Rust enum docs, F# DU, Zod docs, ts-pattern docs).
|
|
- 신뢰도 A.
|
|
|
|
## 🕓 Changelog
|
|
| 날짜 | 변경 |
|
|
|---|---|
|
|
| 2026-05-08 | Phase 1 |
|
|
| 2026-05-10 | Manual cleanup — DU patterns + exhaustive + ts-pattern + Zod |
|