[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,125 +2,206 @@
|
||||
id: wiki-2026-0508-discriminated-unions
|
||||
title: Discriminated Unions
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Tagged Unions, Sum Types, Algebraic Data Types, ADT]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [auto-consolidated, technical-documentation]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [typescript, types, functional, type-narrowing]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: type-system
|
||||
---
|
||||
|
||||
# [[Discriminated Unions|Discriminated Unions]]
|
||||
# Discriminated Unions
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> Discriminated Unions(또는 식별 가능한 유니온, 태그된 유니온)은 서로 다른 데이터 형태를 구분하기 위해 공통된 리터럴 속성(판별자, Discriminant)을 사용하는 TypeScript의 패턴입니다 [1-3]. 일반적인 유니온 타입과 달리, 컴파일러가 판별자 속성을 확인하여 타입을 자동으로 안전하게 좁힐 수(Narrowing) 있게 해줍니다 [4-6]. 이를 통해 유효하지 않은 상태의 표현을 원천적으로 차단하고, 모든 가능한 경우를 처리하도록 강제하는 완전성 검사(Exhaustiveness checking)를 구현할 수 있습니다 [3, 7, 8].
|
||||
## 매 한 줄
|
||||
> **"매 한 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.
|
||||
|
||||
---
|
||||
## 매 핵심
|
||||
|
||||
> "타입의 확실한 이름표: 여러 가능한 데이터 형태 중 '현재 어떤 형태인지'를 명확한 구분자(Tag)로 박제하여, 조건문 안에서 컴파일러가 타입을 완벽하게 추론하게 만들고 런타임 에러의 가능성을 원천 봉쇄하는 견고한 방패."
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **작동 원리 및 특징**
|
||||
Discriminated Union은 객체들이 공통으로 가지는 식별자 필드(주로 `kind`, `type`, `status` 같은 문자열 리터럴)를 활용하여 구성됩니다 [2-4]. 이 공통 속성을 기반으로 TypeScript의 코드 흐름 분석이 진행되며, 특정 브랜치에서 타입을 명확하게 좁혀줍니다 [3, 4, 9]. 이는 런타임 오버헤드가 전혀 추가되지 않는 컴파일 타임 전용 구조입니다 [10].
|
||||
|
||||
* **주요 장점**
|
||||
가장 큰 장점은 올바르지 않은 조합의 상태(Invalid [[State|State]]s)를 코드로 표현할 수 없게 만들어 구조적으로 버그를 방지한다는 것입니다 [1, 7, 11]. 또한 `switch` 문과 `never` 타입을 결합하면 모든 유니온 케이스가 처리되었는지 컴파일러가 확인하는 '완전성 검사(Exhaustive checking)'가 가능합니다 [3, 12-14]. 유니온에 새로운 타입 멤버가 추가되었을 때 이를 누락한 코드를 즉각적인 컴파일 에러로 포착해 내므로 유지보수성이 크게 향상됩니다 [3, 8].
|
||||
|
||||
* **사용 사례 (Use Cases)**
|
||||
API 응답 데이터 처리, 폼(Form) 핸들링, Redux 스타일의 리듀서(Reducer), 라우터 상태 관리, 그리고 상태 머신(State Machine) 패턴을 모델링하는 데 매우 적합합니다 [7, 15-17]. 복잡한 상태를 표현해야 할 때는 다중 판별자(Multiple Discriminants)를 두거나 유니온을 중첩(Nested)하는 방식으로도 활용할 수 있습니다 [15, 16].
|
||||
|
||||
* **주의사항 및 베스트 프랙티스**
|
||||
판별자로는 항상 문자열 리터럴 타입을 사용하는 것이 권장되며, 모든 브랜치에 걸쳐 일관된 판별자 속성을 포함해야 합니다 [12, 16, 18]. 타입을 좁힐 때는 `instanceof` 연산자를 사용하는 대신 반드시 판별자 속성을 확인해야 합니다 [18]. 단, 아주 거대한 코드베이스에서 과도하게 복잡한 유니온 타입을 사용하면 TypeScript의 컴파일 속도가 느려질 수 있으며, 깊게 중첩될 경우 에러 메시지를 파악하기 어려워질 수 있으므로 주의해야 합니다 [10].
|
||||
|
||||
---
|
||||
|
||||
구별된 공용체(Discriminated-Unions, Tagged Unions)는 공통된 문자열 리터럴 속성(Discriminant)을 사용하여 여러 타입 중 하나를 안전하게 선택하는 패턴입니다.
|
||||
|
||||
1. **3대 조건**:
|
||||
* **Union of Types**: 여러 타입이 결합된 합집합 타입.
|
||||
* **Discriminant Property**: 각 타입에 공통으로 존재하는 리터럴 속성 (예: `type: 'success' | 'error'`).
|
||||
* **Type Guarding**: `switch`나 `if` 문을 통해 해당 속성을 검사하면, 블록 내부에서 해당 타입으로만 자동 축소(Narrowing).
|
||||
2. **왜 중요한가?**:
|
||||
* 에러 핸들링 시 `status` 값에 따라 `data`가 있을지 `error`가 있을지 컴파일러가 정확히 알게 하여, 정의되지 않은 속성 접근 정책(Undefined errors)을 막기 때문임. ([[Reliability|Reliability]]와 연결)
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
|
||||
---
|
||||
|
||||
- **과거 데이터와의 충돌**: 과거 자바스크립트 정책은 'duck typing'에 의존하여 런타임에 일일이 `if(data)` 등을 체크해야 했으나, TS 정책은 구별된 공용체 정책을 통해 '컴파일 타임'에 모든 경로 정책을 검증함(RL Update).
|
||||
- **정책 변화(RL Update)**: 이제는 단순 에러 처리를 넘어, 복잡한 상태 머신 정책(FSM)이나 Redux 액션 타입 정책 등을 정의하는 표준 아키텍처 패턴 정책으로 자리 잡음. ([[State-Space|State-Space]]와 연결)
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Union Types|Union Types]], Type Narrowing, Exhaustiveness Checking, Literal Types, never type
|
||||
- **Projects/Contexts:** React State [[Management|Management]], State Machine Pattern, API Response Handling, Redux Reducers
|
||||
- **Contradictions/Notes:** Discriminated Union 패턴은 타입 안정성과 예측 가능성을 크게 높여주지만, 유니온 타입이 지나치게 복잡해지거나 깊은 중첩 구조를 가지게 되면 오히려 TypeScript의 컴파일 성능을 저하시키고 에러 메시지의 가독성을 떨어뜨리는 부작용(단점)을 유발할 수 있습니다 [10].
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
- [[Reliability|Reliability]], [[State-Space|State-Space]], [[Technical-Architecture|Technical-Architecture]], [[Logic|Logic]], [[Complexity-Theory|Complexity-Theory]]
|
||||
- **Key Concept**: Algebraic Data Types (ADT).
|
||||
---
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
### 매 anatomy
|
||||
```typescript
|
||||
type Result<T, E> =
|
||||
| { kind: "ok"; value: T }
|
||||
| { kind: "err"; error: E };
|
||||
// ^^^^^^^^^^^ 매 discriminant — 매 string / number / boolean literal.
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### 매 narrowing rules
|
||||
- 매 discriminant 의 literal 의 must.
|
||||
- 매 `switch` / `if` 매 변수 의 narrow.
|
||||
- 매 exhaustive check 의 `never` 의 leverage.
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 매 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.
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### 매 응용
|
||||
1. Result / Option / Either monads.
|
||||
2. State machine state.
|
||||
3. Redux / xstate action / event.
|
||||
4. API response variants.
|
||||
5. AST node types.
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Pattern 1: Result / Either
|
||||
```typescript
|
||||
type Result<T, E = Error> =
|
||||
| { ok: true; value: T }
|
||||
| { ok: false; error: E };
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
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]] · [[Rust Enums]] · [[F# DU]]
|
||||
- 응용: [[Result Type]] · [[State Machine]] · [[Redux Actions]] · [[Zod]]
|
||||
- Adjacent: [[Pattern Matching]] · [[Exhaustiveness Checking]] · [[ts-pattern]]
|
||||
|
||||
## 🤖 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 |
|
||||
|
||||
Reference in New Issue
Block a user