Files
2nd/10_Wiki/Topic_Programming/Frontend/Discriminated-Unions-for-State-Modeling.md
T
Antigravity Agent 9148c358d0 docs(10_Wiki): 위키 전체 재구성 — Topic_* 폴더를 4개 카테고리로 통합 + 대규모 중복 제거
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 폴더 제거.
2026-07-05 00:33:48 +09:00

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
Tagged Unions
Sum Types
ADT State
none A 0.9 applied
typescript
state-modeling
types
frontend
2026-05-10 pending
language framework
TypeScript React / any

Discriminated Unions for State Modeling

매 한 줄

"매 impossible state 의 unrepresentable". Discriminated union (tagged union, sum type) 으로 매 async/UI state 를 modeling 하면 매 loading + error + data simultaneous 같은 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.

매 응용

  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.

💻 패턴

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

🤖 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