[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,89 +2,197 @@
|
||||
id: wiki-2026-0508-discriminated-unions-for-error-h
|
||||
title: Discriminated Unions for Error Handling
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [TS-UNION-001]
|
||||
aliases: [Tagged Unions, Result Type, Sum Types]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [typescript, type-system, Functional-Programming, error-handling]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [typescript, error-handling, type-system, functional]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
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: none
|
||||
---
|
||||
|
||||
# [[Discriminated Unions|Discriminated Unions]] (판별 가능한 유니온)
|
||||
# Discriminated Unions for Error Handling
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "타입 가드를 자동화하는 영리한 리터럴 태그" — 공통된 속성(Tag)을 기준으로 여러 타입을 하나로 묶고, 코드 레벨에서 안전하게 특정 타입을 식별해낼 수 있게 하는 타입 설계 기법.
|
||||
## 매 한 줄
|
||||
> **"매 throw 의 의 X — return value 의 success/failure 의 model"**. ML/Haskell `Either`, Rust `Result<T, E>` 의 TypeScript port. 2026 의 매 typed exception 의 alternative — exhaustive checking + traceable failure path.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** 여러 객체 타입이 공통적으로 가지는 '태그(Literal property)'를 사용하여 컴파일러가 조건문(`switch`, `if`) 내에서 타입을 정확히 좁힐 수 있도록 돕는 패턴.
|
||||
- **세부 내용:**
|
||||
- **Tag/Kind 속성:** 각 타입에 고유한 문자열 리터럴 속성을 부여하여 구분의 근거를 마련.
|
||||
- **Exhaustiveness Check:** `switch` 문에서 모든 가능한 케이스를 처리했는지 TypeScript 컴파일러가 확인하게 함.
|
||||
- **Error Handling:** `Success`와 `Failure` 타입을 유니온으로 묶어 런타임 에러 대신 컴파일 타임에 예외 처리를 강제.
|
||||
- **Pattern Matching:** 함수형 언어의 패턴 매칭과 유사한 안정성을 객체 지향 환경에서 구현.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** `instanceof`나 임의의 속성 체크 기반의 불안정한 타입 가드에서, 명시적인 '태그' 기반의 선언적 타입 가드로 표준화됨.
|
||||
- **정책 변화:** Antigravity 에이전트의 통신 프로토콜 정의 시, 메시지 타입을 Discriminated Unions로 정의하여 파싱 오류를 원천 차단함.
|
||||
### 매 왜 throw 의 X 의
|
||||
- `throw` 의 type-erased — caller 의 매 catch 의 type 의 unknown.
|
||||
- Control flow 의 invisible — 매 implicit goto.
|
||||
- async 의 매 unhandled rejection 의 silent.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Parent:** 10_Wiki/💡 Topics/AI
|
||||
- **Related:** Type-Guards, Algebraic-Data-Types, [[Exhaustiveness-Checking|Exhaustiveness-Checking]]
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/[[Discriminated-Unions|Discriminated-Unions]]-for-Error-Handling.md
|
||||
### 매 discriminator tag
|
||||
- 매 literal field (`type`, `tag`, `_tag`, `kind`) 의 매 union 의 narrow.
|
||||
- TypeScript 의 control-flow analysis 의 `if (r.type === "ok")` 의 narrow.
|
||||
- exhaustive check 의 `switch` + `never` 의 가능.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. API client (network/parse/validation 의 error 의 분리).
|
||||
2. Form validation (field-level error).
|
||||
3. Parser combinator (success/fail with location).
|
||||
4. State machine (state 의 each 의 tag).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### 기본 Result type
|
||||
```ts
|
||||
type Result<T, E = Error> =
|
||||
| { ok: true; value: T }
|
||||
| { ok: false; 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
|
||||
const ok = <T>(value: T): Result<T, never> => ({ ok: true, value });
|
||||
const err = <E>(error: E): Result<never, E> => ({ ok: false, error });
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Domain error 의 tagged
|
||||
```ts
|
||||
type FetchUserError =
|
||||
| { type: "network"; cause: unknown }
|
||||
| { type: "not_found"; userId: string }
|
||||
| { type: "unauthorized" }
|
||||
| { type: "parse"; raw: unknown; issue: string };
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
async function fetchUser(id: string): Promise<Result<User, FetchUserError>> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`/api/users/${id}`);
|
||||
} catch (cause) {
|
||||
return err({ type: "network", cause });
|
||||
}
|
||||
if (res.status === 404) return err({ type: "not_found", userId: id });
|
||||
if (res.status === 401) return err({ type: "unauthorized" });
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const raw = await res.json();
|
||||
const parsed = UserSchema.safeParse(raw);
|
||||
if (!parsed.success) {
|
||||
return err({ type: "parse", raw, issue: parsed.error.message });
|
||||
}
|
||||
return ok(parsed.data);
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Exhaustive handling
|
||||
```ts
|
||||
function renderError(e: FetchUserError): string {
|
||||
switch (e.type) {
|
||||
case "network": return "Network failure. Retry?";
|
||||
case "not_found": return `User ${e.userId} 의 X.`;
|
||||
case "unauthorized": return "Login 의 필요.";
|
||||
case "parse": return `Bad response: ${e.issue}`;
|
||||
default: {
|
||||
const _exhaustive: never = e; // 매 compile error 의 새 case 의 추가 시
|
||||
return _exhaustive;
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Caller 의 narrow 의 사용
|
||||
```ts
|
||||
const r = await fetchUser("abc");
|
||||
if (!r.ok) {
|
||||
// r.error: FetchUserError — 매 fully typed
|
||||
return renderError(r.error);
|
||||
}
|
||||
// r.value: User — 매 narrowed
|
||||
console.log(r.value.email);
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Combinator (map / flatMap)
|
||||
```ts
|
||||
function map<T, U, E>(r: Result<T, E>, f: (t: T) => U): Result<U, E> {
|
||||
return r.ok ? ok(f(r.value)) : r;
|
||||
}
|
||||
|
||||
function flatMap<T, U, E>(r: Result<T, E>, f: (t: T) => Result<U, E>): Result<U, E> {
|
||||
return r.ok ? f(r.value) : r;
|
||||
}
|
||||
|
||||
// 매 chained pipeline
|
||||
const result = flatMap(
|
||||
await fetchUser(id),
|
||||
(u) => u.verified ? ok(u) : err({ type: "unauthorized" } as FetchUserError),
|
||||
);
|
||||
```
|
||||
|
||||
### Form validation
|
||||
```ts
|
||||
type FieldResult<T> =
|
||||
| { state: "valid"; value: T }
|
||||
| { state: "invalid"; reasons: string[] }
|
||||
| { state: "pending" };
|
||||
|
||||
function validateEmail(s: string): FieldResult<string> {
|
||||
if (s.length === 0) return { state: "pending" };
|
||||
const reasons: string[] = [];
|
||||
if (!s.includes("@")) reasons.push("@ missing");
|
||||
if (s.length > 254) reasons.push("Too long");
|
||||
return reasons.length ? { state: "invalid", reasons } : { state: "valid", value: s };
|
||||
}
|
||||
```
|
||||
|
||||
### Zod 의 native return
|
||||
```ts
|
||||
import { z } from "zod";
|
||||
|
||||
const UserSchema = z.object({ id: z.string(), email: z.email() });
|
||||
const parsed = UserSchema.safeParse(input);
|
||||
// parsed: { success: true; data: User } | { success: false; error: ZodError }
|
||||
```
|
||||
|
||||
### neverthrow 라이브러리 (2026 standard)
|
||||
```ts
|
||||
import { ok, err, Result, ResultAsync } from "neverthrow";
|
||||
|
||||
const fetchUserSafe = (id: string): ResultAsync<User, FetchUserError> =>
|
||||
ResultAsync.fromPromise(fetch(`/api/users/${id}`), (c) => ({ type: "network", cause: c } as const))
|
||||
.andThen((res) =>
|
||||
res.ok ? ResultAsync.fromSafePromise(res.json()) : err({ type: "not_found", userId: id } as const)
|
||||
);
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Domain logic 의 expected failure | Discriminated union Result |
|
||||
| Truly exceptional (OOM, bug) | Throw |
|
||||
| Async I/O | `Promise<Result<T, E>>` 의 neverthrow `ResultAsync` |
|
||||
| Schema parsing | Zod `safeParse` |
|
||||
| Multi-step pipeline | `flatMap` chain 의 Effect TS |
|
||||
|
||||
**기본값**: domain error 의 tagged union, infrastructure error 의 throw.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[TypeScript]] · [[Type System]]
|
||||
- 변형: [[Effect TS 및 ts-brand 라이브러리 활용]] · [[Either Monad]]
|
||||
- 응용: [[Error Boundaries]] · [[Form Validation]] · [[API Client Design]]
|
||||
- Adjacent: [[Zod]] · [[Pattern Matching]] · [[Exhaustive Checking]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: domain error 의 modeling, exhaustive switch 의 enforce, async error path 의 explicit.
|
||||
**언제 X**: panic-level error (assertion fail) — throw 의 더 적합.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **`{ error: string | null; data: T | null }`**: 매 implicit invariant — 둘 모두 null/non-null 의 type 의 allow.
|
||||
- **String-only error**: 매 i18n / programmatic handling 의 X.
|
||||
- **Discriminator 의 `boolean`**: `ok: true/false` 의 OK, but multi-variant 의 X — string literal 의 사용.
|
||||
- **Throw inside Result-returning fn**: 매 hybrid 의 worst.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (TypeScript handbook, Effect-TS docs, neverthrow, Rust `Result`, fp-ts `Either`).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — exhaustive check + neverthrow + combinators 추가 |
|
||||
|
||||
Reference in New Issue
Block a user