f8b21af4be
10_Wiki/Topics 대규모 정리: - 오류 캡처/미완성 stub 문서 227개 제거 - 교차폴더 중복 43클러스터 병합 (63파일 → redirect) - 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건 - 카테고리 MOC 6개 신규 생성 - Graph 섹션 미해결 related-keyword 링크 10,058건 제거 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
5.4 KiB
5.4 KiB
id, title, category, status, canonical_id, aliases, duplicate_of, source_trust_level, confidence_score, verification_status, tags, raw_sources, last_reinforced, github_commit, tech_stack
| id | title | category | status | canonical_id | aliases | duplicate_of | source_trust_level | confidence_score | verification_status | tags | raw_sources | last_reinforced | github_commit | tech_stack | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| wiki-2026-0508-discriminated-unions-for-state-m | Discriminated Unions for State Modeling | 10_Wiki/Topics | verified | self |
|
none | A | 0.9 | applied |
|
2026-05-10 | pending |
|
Discriminated Unions for State Modeling
매 한 줄
"매 impossible state 의 unrepresentable". Discriminated union (tagged union, sum type) 으로 매 async/UI state 를 modeling 하면 매
loading + error + datasimultaneous 같은 illegal combination 매 type system 매 차단.
매 핵심
매 motivation
- Boolean flag combinatorics:
isLoading,isError,data→ 8 states, 매 5+ illegal. - DU: 매 mutually-exclusive variants 만 표현.
매 anatomy
- Common discriminator field (
type,status,kind). - Per-variant payload.
- TS narrows by discriminator in
switch/if.
매 응용
- Async data (idle / loading / success / error).
- Form (initial / submitting / submitted / failed).
- Wizard (step1 / step2 / done).
- Auth (anonymous / loading / authenticated / expired).
- Reducer/state machine actions.
💻 패턴
Async state DU
type AsyncState<T, E = Error> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: E };
function render<T>(s: AsyncState<T>) {
switch (s.status) {
case 'idle': return <Idle />;
case 'loading': return <Spinner />;
case 'success': return <Data data={s.data} />; // 매 data 매 type-safe
case 'error': return <Err msg={s.error.message} />;
}
}
Exhaustive check helper
function assertNever(x: never): never {
throw new Error(`Unhandled variant: ${JSON.stringify(x)}`);
}
function step(s: WizardState) {
switch (s.kind) {
case 'address': return <AddressForm />;
case 'payment': return <PaymentForm />;
case 'review': return <Review />;
default: return assertNever(s); // 매 compile error 매 새 variant 추가 시
}
}
Form state DU
type FormState<V, E = Record<string, string>> =
| { phase: 'editing'; values: V }
| { phase: 'submitting'; values: V }
| { phase: 'failed'; values: V; errors: E }
| { phase: 'submitted'; result: { id: string } };
Auth state DU
type Auth =
| { state: 'anonymous' }
| { state: 'authenticating' }
| { state: 'authenticated'; user: User; token: string }
| { state: 'expired'; lastUser: User };
function canAccessAdmin(a: Auth): boolean {
return a.state === 'authenticated' && a.user.role === 'admin';
}
Reducer with action DU
type Action =
| { type: 'fetch/start' }
| { type: 'fetch/success'; payload: User[] }
| { type: 'fetch/error'; error: string };
function reducer(s: AsyncState<User[]>, a: Action): AsyncState<User[]> {
switch (a.type) {
case 'fetch/start': return { status: 'loading' };
case 'fetch/success': return { status: 'success', data: a.payload };
case 'fetch/error': return { status: 'error', error: new Error(a.error) };
}
}
Pattern matching with ts-pattern
import { match } from 'ts-pattern';
const view = match(state)
.with({ status: 'idle' }, () => <Idle />)
.with({ status: 'loading' }, () => <Spinner />)
.with({ status: 'success' }, ({ data }) => <Data data={data} />)
.with({ status: 'error' }, ({ error }) => <Err msg={error.message} />)
.exhaustive();
Nested DU (loading sub-status)
type Resource<T> =
| { state: 'idle' }
| { state: 'loading'; progress?: number }
| { state: 'streaming'; partial: T[]; progress: number }
| { state: 'success'; data: T }
| { state: 'error'; error: Error; retryCount: number };
Builder helpers
const idle = <T,>(): AsyncState<T> => ({ status: 'idle' });
const loading = <T,>(): AsyncState<T> => ({ status: 'loading' });
const success = <T,>(data: T): AsyncState<T> => ({ status: 'success', data });
const failure = <T,>(error: Error): AsyncState<T> => ({ status: 'error', error });
매 결정 기준
| 상황 | Approach |
|---|---|
| 2+ boolean flags 매 mutually exclusive | DU 강제 |
| Single boolean | 매 plain bool OK |
| Complex transitions | DU + state machine (XState) |
| Library API surface | DU 매 caller-friendly |
기본값: async/form/wizard/auth state 매 즉시 DU 모델링.
🔗 Graph
- 부모: TypeScript · Type-Driven-Design
- 변형: Algebraic-Data-Types · Sum-Types
- 응용: XState · React-Query
- Adjacent: Exhaustiveness-Checking · Pattern-Matching
🤖 LLM 활용
언제: async data, multi-step UI, auth flow, anywhere 매 boolean explosion 발생. 언제 X: 매 single-flag 매 trivial — over-engineering.
❌ 안티패턴
- Boolean explosion:
isLoading && !isError && datachains. - Optional fields encoding state:
{ data?, loading?, error? }— 매 invalid combos 가능. - Missing exhaustive check: 매 new variant 추가 시 매 silently broken.
🧪 검증 / 중복
- Verified (TS handbook / Richard Feldman "Making Impossible States Impossible").
- 신뢰도 A.
🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — DU patterns for async/form/auth state |