--- id: [[P-Reinforce|P-Reinforce]]-AI-DU-[[State|State]]S category: Unified confidence_score: 0.99 tags: [TypeScript, State[[Management|Management]], Patterns, [[Architecture|Architecture]]] last_reinforced: 2026-04-20 --- # [[Discriminated-Unions-for-State-Modeling|Discriminated-Unions-for-State-Modeling]] (상태 모델링을 위한 구별된 유니온) ## 📌 한 줄 통찰 (The Karpathy Summary) > "불가능한 상태(Impossible State)를 코드 수준에서 원천 봉쇄하라." 로딩 중이면서 동시에 에러가 날 수 없는 것처럼, 시스템의 상호 배타적인 상태들을 타입을 통해 완벽하게 정의하는 기법이다. ## 📖 구조화된 지식 (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**: 컴포넌트나 로직에서 조건문 분기가 매우 명확해지며, 런타임 에러 발생 가능성이 획기적으로 줄어든다. ## ⚠️ 모순 및 업데이트 (RL Update) - 상태가 복잡해지면(예: 부분적 성공, 멀티 스텝 폼 등) 유니온의 조합이 기하급수적으로 늘어날 수 있다. 이때는 상태 머신(State Machine, 예: XState) 라이브러리를 도입하여 타입 안전성과 비즈니스 흐름 제어를 동시에 잡는 것이 권장된다. ## 🔗 지식 연결 (Graph) - Related: [[Discriminated-Unions|Discriminated-Unions]] , [[Finite-State-Machines|Finite-State-Machines]] - Context: React-Query-Pattern