[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,88 +2,180 @@
id: wiki-2026-0508-discriminated-unions-for-state-m
title: Discriminated Unions for State Modeling
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AI-DU-StateS]
aliases: [Tagged Unions, Sum Types, ADT State]
duplicate_of: none
source_trust_level: A
confidence_score: 0.99
tags: [TypeScript, StateManagement, Patterns, Architecture]
confidence_score: 0.9
verification_status: applied
tags: [typescript, state-modeling, types, frontend]
raw_sources: []
last_reinforced: 2026-04-20
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: React / any
---
# [[Discriminated-Unions-for-State-Modeling|Discriminated-Unions-for-State-Modeling]] (상태 모델링을 위한 구별된 유니온)
# Discriminated Unions for State Modeling
## 📌 한 줄 통찰 (The Karpathy Summary)
> "불가능한 상태(Impossible State)를 코드 수준에서 원천 봉쇄하라." 로딩 중이면서 동시에 에러가 날 수 없는 것처럼, 시스템의 상호 배타적인 상태들을 타입을 통해 완벽하게 정의하는 기법이다.
## 한 줄
> **"매 impossible state 의 unrepresentable"**. Discriminated union (tagged union, sum type) 으로 매 async/UI state 를 modeling 하면 매 `loading + error + data` simultaneous 같은 illegal combination 매 type system 매 차단.
## 📖 구조화된 지식 (Synthesized Content)
- **The Anti-pattern**:
- `interface State { isLoading: boolean; error?: string; data?: Data; }`
- 이 설계는 `isLoading: true`이면서 동시에 `error`가 존재하는 모순된 상태를 허용한다.
- **The Discriminated Union [[Solution|Solution]]**:
- `type State = { type: 'loading' } | { type: 'error'; message: string } | { type: 'success'; data: Data };`
- `type` 속성을 통해 현재 어떤 상태인지 명확히 구별하며, 각 상태에 꼭 필요한 데이터만 가질 수 있게 강제한다.
- **Benefit**: 컴포넌트나 로직에서 조건문 분기가 매우 명확해지며, 런타임 에러 발생 가능성이 획기적으로 줄어든다.
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 상태가 복잡해지면(예: 부분적 성공, 멀티 스텝 폼 등) 유니온의 조합이 기하급수적으로 늘어날 수 있다. 이때는 상태 머신(State Machine, 예: XState) 라이브러리를 도입하여 타입 안전성과 비즈니스 흐름 제어를 동시에 잡는 것이 권장된다.
### 매 motivation
- Boolean flag combinatorics: `isLoading`, `isError`, `data` → 8 states, 매 5+ illegal.
- DU: 매 mutually-exclusive variants 만 표현.
## 🔗 지식 연결 (Graph)
- Related: [[Discriminated-Unions|Discriminated-Unions]] , [[Finite-State-Machines|Finite-State-Machines]]
- Context: React-Query-Pattern
### 매 anatomy
- Common discriminator field (`type`, `status`, `kind`).
- Per-variant payload.
- TS narrows by discriminator in `switch` / `if`.
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 매 응용
1. Async data (idle / loading / success / error).
2. Form (initial / submitting / submitted / failed).
3. Wizard (step1 / step2 / done).
4. Auth (anonymous / loading / authenticated / expired).
5. Reducer/state machine actions.
**언제 이 지식을 쓰는가:**
- *(TODO)*
## 💻 패턴
**언제 쓰면 안 되는가:**
- *(TODO)*
### Async state DU
```ts
type AsyncState<T, E = Error> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; error: E };
## 🧪 검증 상태 (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
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} />;
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Exhaustive check helper
```ts
function assertNever(x: never): never {
throw new Error(`Unhandled variant: ${JSON.stringify(x)}`);
}
**선택 A를 써야 할 때:**
- *(TODO)*
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 추가 시
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Form state DU
```ts
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 } };
```
**기본값:**
> *(TODO)*
### Auth state DU
```ts
type Auth =
| { state: 'anonymous' }
| { state: 'authenticating' }
| { state: 'authenticated'; user: User; token: string }
| { state: 'expired'; lastUser: User };
## ❌ 안티패턴 (Anti-Patterns)
function canAccessAdmin(a: Auth): boolean {
return a.state === 'authenticated' && a.user.role === 'admin';
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Reducer with action DU
```ts
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`
```ts
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)
```ts
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
```ts
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]]
- 변형: [[State-Machines]] · [[Algebraic-Data-Types]] · [[Sum-Types]]
- 응용: [[XState]] · [[ts-pattern]] · [[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 && data` chains.
- **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 |