[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,114 +2,248 @@
id: wiki-2026-0508-exhaustiveness-checking
title: Exhaustiveness Checking
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: []
aliases: [exhaustive match, never type, sealed types, tagged union, switch exhaustive]
duplicate_of: none
source_trust_level: A
confidence_score: 0.92
tags: [auto-consolidated, technical-documentation]
confidence_score: 0.95
verification_status: applied
tags: [type-system, typescript, rust, exhaustive, never-type, discriminated-union]
raw_sources: []
last_reinforced: 2026-05-08
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 / Rust / Kotlin
---
# [[Exhaustiveness-Checking|Exhaustiveness-Checking]] (망라성 검사)
# Exhaustiveness Checking
## 📌 한 줄 통찰 (The Karpathy Summary)
> "빠진 케이스가 없는지 컴파일러가 대신 체크하는 완벽주의자의 도구." 모든 가능한 타입 시나리오를 처리했음을 논리적으로 보장하여, 나중에 새로운 타입이 추가되었을 때 발생할 수 있는 런타임 에러를 원천 봉쇄하는 기법이다.
## 한 줄
> **"매 type-level 의 매 case 의 covered 의 verify"**. 매 switch / match 의 missing branch 의 compile-time 의 catch. 매 TypeScript `never`, 매 Rust `match`, 매 Kotlin sealed. 매 modern: 매 type-driven design 의 핵심.
---
## 매 핵심
> 완전성 검사(Exhaustiveness Checking)는 타입 시스템 내에서 특정 유니온 타입의 모든 가능한 케이스(변형)가 코드상에서 빠짐없이 처리되었는지를 컴파일 시점에 검증하는 기법입니다[1-3]. 식별 가능한 유니온([[Discriminated Unions|Discriminated Unions]])과 함께 결합하여 주로 사용되며, 새로운 상태가 추가되었을 때 이를 처리하지 않은 분기문이 존재하면 즉시 컴파일 에러를 발생시킵니다[2, 3]. 이를 통해 개발자는 런타임 버그를 사전에 예방하고 잘못된 상태가 시스템을 통과하는 것을 원천적으로 차단할 수 있습니다[4, 5].
### 매 mechanism
- **Discriminated union** + 매 switch.
- **Sealed types**: 매 known set.
- **never type** (TS): 매 unreachable.
- **Pattern match** (Rust, Scala, Kotlin).
## 📖 구조화된 지식 (Synthesized Content)
- **The Never Trick**:
- 타입스크립트의 `never` 타입을 활용한다. 모든 조건문(if/switch)이 끝난 뒤 `default` 케이스에 `const _check: never = remainValue;`를 할당한다.
- **How it works**:
- 만약 처리하지 않은 타입이 남아 있다면, 그 값은 `never` 타입에 할당될 수 없으므로 컴파일 에러가 발생한다.
- **Value**:
- 코드 유지보수 시 강력한 안전장치가 된다. 예를 들어 `UserRole`에 'Guest'가 새로 추가되면, 이를 처리하지 않은 모든 스위치 문에서 즉시 빨간 줄이 그어진다.
### 매 응용
1. **State machine**: 매 모든 state 의 handle.
2. **Event handler**: 매 모든 event.
3. **Error type**: 매 union of errors.
4. **API response**.
5. **Theme / variant**.
---
## 💻 패턴
- **기본 작동 원리:** 완전성 검사는 데이터의 모든 가능한 형태가 `switch` 문 등의 분기 구조에서 명시적으로 다루어졌는지 확인합니다[1, 2]. 특정 유니온 타입에 새로운 형태(Shape)나 상태를 추가했지만, 이를 제어문에서 처리하는 코드를 작성하는 것을 잊었다면, 컴파일러는 누락된 부분에 대해 에러를 던집니다[2, 3]. 이는 런타임에 발생할 수 있는 잠재적 결함을 컴파일 시점의 에러로 전환해 줍니다[3-5].
- **`never` 타입을 활용한 검사 기법:** TypeScript에서 완전성 검사를 구현하는 가장 확실한 방법 중 하나는 `never` 타입을 사용하는 것입니다[3, 6, 7]. 모든 유효한 케이스를 걸러낸 후 남은 값을 `never` 타입(예: `assertNever` 함수 등)으로 할당하도록 작성합니다[7]. 만약 개발자가 실수로 특정 케이스를 누락했다면, 남은 값은 `never`가 아닌 실제 타입(누락된 타입)을 가지게 되어 컴파일 에러가 발생하며, 에러 메시지를 통해 어떤 타입이 누락되었는지 명확히 알 수 있습니다[3, 7].
- **`strictNullChecks`를 활용한 반환 타입 검사:** 또 다른 방법으로는 TypeScript의 `strictNullChecks` 기능을 켜고 함수에 명시적인 반환 타입을 지정하는 방식이 있습니다[6]. 모든 케이스를 철저히 처리하지 않은 분기문은 암묵적으로 `undefined`를 반환할 가능성을 내포하게 되므로, 반환 타입 규칙 위반으로 에러를 발생시켜 완전성을 강제할 수 있습니다[6].
- **다양한 환경에서의 활용 패턴:** TypeScript의 기본 제어 구조뿐만 아니라, `ts-pattern`과 같은 패턴 매칭 라이브러리에서도 `.exhaustive()` 문법을 활용하여 처리되지 않은 케이스를 타입스크립트 컴파일러가 감지하도록 돕습니다[8]. 또한 C#과 같은 다른 언어 환경에서도, 결과를 철저히 소진(exhausting)하지 않으면 컴파일이 되지 않게 구조화하여 오류를 안전하게 처리하는 동일한 목적의 설계 방식이 사용됩니다[9].
### TypeScript (never)
```typescript
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; side: number }
| { kind: 'rectangle'; w: number; h: number };
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- 망라성 검사는 '닫힌 시스템(Closed[[_system|system]])'에서는 완벽하지만, 외부 라이브러리에서 동적으로 확장되는 타입에 대해서는 무력할 수 있다. 이때는 `assertNever`와 같은 헬퍼 함수를 사용하여 런타임 에러를 명시적으로 던지도록 설계해야 한다.
---
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 🔗 지식 연결 (Graph)
- Related: [[Discriminated-Unions|Discriminated-Unions]] , Type-Soundness
- Tool: TypeScript Compiler (tsc)
---
- **Related Topics:** 식별 가능한 유니온(Discriminated Unions), [[never 타입|never 타입]], [[타입 좁히기 (Type Narrowing)|타입 좁히기(Type Narrowing]]
- **Projects/Contexts:** TypeScript 컴파일러의 정적 타입 시스템, 패턴 매칭 라이브러리(ts-pattern 등)
- **Contradictions/Notes:** TypeScript에서 `strictNullChecks`를 활용한 반환 타입 검사 방식은 구형 코드베이스에서 항상 원활하게 작동하지 않을 수 있으며 다소 미묘한 방식인 반면, `never` 타입을 활용한 검사 방식은 오류 메시지에 누락된 타입 이름이 포함되어 더 명확하게 문제를 파악할 수 있다는 장점이 있습니다[6, 7].
---
*Last updated: 2026-04-18*
---
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
**언제 이 지식을 쓰는가:**
- *(TODO)*
**언제 쓰면 안 되는가:**
- *(TODO)*
## 🧪 검증 상태 (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 area(s: Shape): number {
switch (s.kind) {
case 'circle': return Math.PI * s.radius ** 2;
case 'square': return s.side ** 2;
case 'rectangle': return s.w * s.h;
default: {
const _exhaustive: never = s; // 매 compile error if Shape grows
throw new Error(`Unhandled: ${_exhaustive}`);
}
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### assertNever helper
```typescript
function assertNever(x: never): never {
throw new Error(`Unexpected: ${JSON.stringify(x)}`);
}
**선택 A를 써야 할 때:**
- *(TODO)*
function handle(s: Shape) {
switch (s.kind) {
case 'circle': return ...;
case 'square': return ...;
case 'rectangle': return ...;
default: return assertNever(s);
}
}
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Rust (match)
```rust
enum Shape {
Circle { radius: f64 },
Square { side: f64 },
Rectangle { w: f64, h: f64 },
}
**기본값:**
> *(TODO)*
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
Shape::Square { side } => side * side,
Shape::Rectangle { w, h } => w * h,
// 매 missing arm = compile error
}
}
```
## ❌ 안티패턴 (Anti-Patterns)
### Kotlin sealed class
```kotlin
sealed class Shape {
data class Circle(val r: Double) : Shape()
data class Square(val side: Double) : Shape()
}
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
fun area(s: Shape) = when (s) {
is Shape.Circle -> Math.PI * s.r * s.r
is Shape.Square -> s.side * s.side
// 매 exhaustive — 매 compiler enforces
}
```
### State machine (TS)
```typescript
type AppState =
| { status: 'idle' }
| { status: 'loading'; startedAt: Date }
| { status: 'success'; data: Data }
| { status: 'error'; message: string };
function render(s: AppState) {
switch (s.status) {
case 'idle': return <Welcome />;
case 'loading': return <Spinner />;
case 'success': return <Display data={s.data} />;
case 'error': return <Error msg={s.message} />;
default: return assertNever(s);
}
}
```
### Result type
```typescript
type Result<T, E> = { tag: 'ok'; value: T } | { tag: 'err'; error: E };
function handle<T, E>(r: Result<T, E>): T {
switch (r.tag) {
case 'ok': return r.value;
case 'err': throw r.error;
default: return assertNever(r);
}
}
```
### Reducer (Redux)
```typescript
type Action =
| { type: 'add'; value: number }
| { type: 'sub'; value: number }
| { type: 'reset' };
function reducer(state: number, action: Action): number {
switch (action.type) {
case 'add': return state + action.value;
case 'sub': return state - action.value;
case 'reset': return 0;
default: return assertNever(action);
}
}
```
### Type predicate (narrow)
```typescript
function isCircle(s: Shape): s is Extract<Shape, { kind: 'circle' }> {
return s.kind === 'circle';
}
```
### TS 4.4+ template literal (string union)
```typescript
type HttpStatus = 200 | 404 | 500;
function describe(s: HttpStatus): string {
switch (s) {
case 200: return 'OK';
case 404: return 'Not Found';
case 500: return 'Server Error';
default: return assertNever(s);
}
}
```
### Compile fail demo
```typescript
type Theme = 'light' | 'dark' | 'sepia';
function bg(t: Theme): string {
switch (t) {
case 'light': return '#fff';
case 'dark': return '#000';
// 매 missing 'sepia'
default: const _: never = t; // ❌ Type 'sepia' is not assignable to 'never'
return '';
}
}
```
### ESLint rule
```javascript
// .eslintrc
{
rules: {
'@typescript-eslint/switch-exhaustiveness-check': 'error',
}
}
```
### Rust if-let / match guard
```rust
match (state, action) {
(State::Idle, Action::Start) => State::Running,
(State::Running, Action::Stop) => State::Idle,
(s, _) => s, // 매 catchall — 매 explicit 의 careful
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| TS state machine | Discriminated union + never |
| Rust enum | match (built-in) |
| Kotlin | sealed + when |
| Redux | tagged action + assertNever |
| API variant | Discriminated union |
| Throwaway script | Skip |
**기본값**: 매 TS = discriminated union + assertNever + ESLint rule. 매 Rust = match. 매 Kotlin = sealed when.
## 🔗 Graph
- 부모: [[Type-System]] · [[Static-Analysis]]
- 변형: [[Discriminated-Union]] · [[Sealed-Class]] · [[Pattern-Matching]]
- 응용: [[State-Machine]] · [[Reducer]] · [[Result-Type]]
- Adjacent: [[Encapsulation-of-Domain-Invariants]] · [[Type-Driven-Design]] · [[Never-Type]]
## 🤖 LLM 활용
**언제**: 매 type-rich domain. 매 state machine. 매 reducer.
**언제 X**: 매 dynamic / heterogeneous.
## ❌ 안티패턴
- **Catchall default**: 매 exhaustiveness 의 lose.
- **String enum 의 boolean check**: 매 brittle.
- **No assertNever**: 매 default 의 silent.
- **Mix kind tag**: 매 narrow 의 fail.
- **Lint disabled**: 매 enforce X.
## 🧪 검증 / 중복
- Verified (TS handbook, Rust book, Effective TypeScript).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — never + 매 TS / Rust / Kotlin / Redux exhaustive code |