[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
+195 -66
View File
@@ -2,92 +2,221 @@
id: wiki-2026-0508-never-타입
title: never 타입
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-5297D4]
aliases: [never, never type, TypeScript never, bottom type]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [typescript, never, exhaustiveness, type-system, bottom-type]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - never 타입"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: typescript-5
---
# [[never 타입|never 타입]]
# never 타입
## 📌 한 줄 통찰 (The Karpathy Summary)
> `never` 타입은 TypeScript에서 결코 발생할 수 없는 값이나 완료되지 않는 상태를 의미하는 타입이다 [1, 2]. 주로 무한 루프나 예외를 던지는 함수의 반환 타입으로 쓰이며, 집합론적으로 '빈 집합'을 나타내어 컴파일러의 완전성 검사(Exhaustiveness checking) 및 엄격한 타입 통제를 구현하는 데 핵심적으로 사용된다 [3, 4].
## 한 줄
> **"매 TypeScript 의 bottom type — 매 absurd, 매 도달 불가능한 value 의 type"**. 매 throw 함수 / infinite loop / exhaustive switch 의 missed case 표현. 매 `never` 매 모든 type 의 subtype, 매 union 에서 absorbed, 매 conditional type 의 filter. 매 type-driven design 의 핵심.
## 📖 구조화된 지식 (Synthesized Content)
- **집합론적 의미와 동작 원리:** TypeScript 타입 시스템을 집합으로 접근할 때, `never`는 어떠한 요소도 가지지 않는 '빈 집합(∅)'을 의미한다 [3, 5]. 빈 집합은 모든 집합의 부분집합이므로 `never` 타입은 모든 타입에 할당될 수 있다(즉, `never extends T`는 항상 참이다) [6]. 하지만 반대로 `never` 자신을 제외한 어떤 타입도 `never`에 할당될 수 없다 [6]. 유니온 타입 및 교집합 연산에서는 `A & never = never`, `A | never = A`의 결과를 산출한다 [3, 7].
- **완전성 검사 (Exhaustiveness Checking):** 식별 가능한 유니온([[Discriminated Unions|Discriminated Unions]])을 활용할 때, switch문 등에서 모든 분기를 처리했는지 컴파일 타임에 강제하기 위해 사용된다 [4, 8]. 모든 유효한 케이스를 걸러내고 남은 기본(default) 상태를 `never` 타입 변수에 할당하도록 구성하면, 추후 유니온에 새로운 타입이 추가되었을 때 처리하지 않은 케이스가 있다면 컴파일 에러를 발생시켜 안전성을 보장한다 [4, 9].
- **초과 속성 차단 및 배타적 속성 관리:** 객체 할당 시 예기치 않은 잉여 속성을 잡아내기 위해 특정 속성을 `never`로 선언하는 기법이 쓰인다 [10, 11]. `never`는 어떠한 값과도 호환되지 않으므로, 들어오면 안 되는 속성을 `never`로 매핑하면 값이 전달될 때 타입 에러를 유발하여 잘못된 사용을 막는다 [10, 12]. 이와 유사하게 판별자(discriminant) 없이 상호 배타적인 속성을 설계할 때, 한쪽이 활성화되면 다른 쪽의 속성을 `never` 타입으로 처리하여 섞임 현상을 방지할 수 있다 [13].
- **함수 반환 타입에서의 활용:** 예외(Error)를 던져 프로그램의 정상 흐름을 중단하거나 무한 루프를 도는 등, 결코 정상적으로 완료되지 않는 함수의 반환 타입으로 명시한다 [2, 14].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 정체
- **Bottom type**: 매 모든 type 의 subtype — 매 `never extends T` 매 항상 true.
- **Empty set**: 매 어떤 value 도 가질 수 없음 — 매 `const x: never = ...` 매 항상 error.
- **Union absorption**: 매 `T | never` = `T`. 매 union 에서 사라짐.
- **Intersection 의 sink**: 매 `T & never` = `never`. 매 incompatible intersection 의 결과.
## 🔗 지식 연결 (Graph)
- **Related Topics:** 유니온 타입 ([[Union Types|Union Types]]), 식별 가능한 유니온 (Discriminated Unions), 집합론 (Set Theory), 초과 속성 검사 ([[Excess Property Checking|Excess Property Checking]]
- **Projects/Contexts:** TypeScript 상태 관리 및 에러 처리 방어 ([[State|State]] [[Management|Management]] and Defensive Error Handling)
- **Contradictions/Notes:** `never``void`는 기능적으로 다르다. 함수가 정상적으로 실행을 마치고 아무 값도 반환하지 않는 경우(실제로는 `undefined`를 반환)에는 `void`를 써야 하며, 예외를 던지거나 영원히 종료되지 않아 실행 흐름이 끝에 도달하지 못하는 경우에만 `never`를 사용해야 한다 [2, 14].
### 매 발생 case
- 매 함수 의 `throw` 만: `function fail(): never { throw Error(); }`.
- 매 infinite loop: `function loop(): never { while (true) {} }`.
- 매 narrow 후 impossible: `if (typeof x === 'string' && typeof x === 'number')` 안 의 `x``never`.
- 매 exhaustive switch 의 default: 매 모든 case handle 후 default 의 `_: never`.
---
*Last updated: 2026-04-18*
### 매 응용
1. **Exhaustiveness check**: switch 의 모든 case 처리 강제.
2. **Conditional type filter**: `T extends X ? T : never` — narrow union.
3. **Impossible state**: 매 type 으로 state 불가능 표현.
4. **Function overload sentinel**: 매 reachable 못한 overload 의 표시.
5. **Branded type uniqueness**: `__brand: never` field.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### Exhaustive switch
```ts
type Shape =
| { kind: 'circle'; radius: number }
| { kind: 'square'; size: number }
| { kind: 'triangle'; base: number; height: number };
**언제 이 지식을 쓰는가:**
- *(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.size ** 2;
case 'triangle': return 0.5 * s.base * s.height;
default:
const _exhaustive: never = s;
// 매 새 shape 추가 시 여기서 type error → 모든 case handle 강제
throw new Error(`Unhandled: ${_exhaustive}`);
}
}
```
## 🤔 의사결정 기준 (Decision Criteria)
### Conditional type filter
```ts
type NonNullable<T> = T extends null | undefined ? never : T;
**선택 A를 써야 할 때:**
- *(TODO)*
type Result = NonNullable<string | null | undefined>;
// 매 string
**선택 B를 써야 할 때:**
- *(TODO)*
type Extract<T, U> = T extends U ? T : never;
type StringOnly = Extract<string | number | boolean, string>;
// 매 string
```
**기본값:**
> *(TODO)*
### assertNever utility
```ts
function assertNever(x: never): never {
throw new Error(`Unexpected: ${JSON.stringify(x)}`);
}
## ❌ 안티패턴 (Anti-Patterns)
function handleEvent(e: 'click' | 'hover' | 'focus') {
switch (e) {
case 'click': return ...;
case 'hover': return ...;
case 'focus': return ...;
default: return assertNever(e); // 매 type-safe + runtime safety
}
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Impossible state via never
```ts
type LoadingState =
| { status: 'idle'; data: never; error: never }
| { status: 'loading'; data: never; error: never }
| { status: 'success'; data: User; error: never }
| { status: 'error'; data: never; error: string };
function render(s: LoadingState) {
if (s.status === 'success') s.data; // 매 User
if (s.status === 'error') s.error; // 매 string
// 매 never field 매 access 시 type error
}
```
### Throw helper
```ts
function unreachable(msg: string): never {
throw new Error(`Unreachable: ${msg}`);
}
function divide(a: number, b: number): number {
if (b === 0) return unreachable('division by zero');
return a / b;
// 매 unreachable 매 never 반환 → narrow 가능
}
```
### Branded type — uniqueness via never
```ts
type Brand<T, B> = T & { readonly __brand: B };
type UserId = Brand<string, 'UserId'>;
type PostId = Brand<string, 'PostId'>;
const u: UserId = 'abc' as UserId;
const p: PostId = u; // 매 type error — different brands
// 매 __brand 가 never 도 가능: type Brand<T, B> = T & { readonly __brand: never };
// (단 distinct brand 위해 phantom 필요)
```
### Distributive conditional with never
```ts
type Filter<T, U> = T extends U ? T : never;
type Foo = Filter<'a' | 'b' | 1 | 2, string>;
// 매 'a' | 'b' — 매 distributive 하게 each variant 검사,
// 매 number variant 매 never 로 배제.
```
### Function overload — never as sentinel
```ts
function fetchUser(): Promise<User>;
function fetchUser(id: string): Promise<User | null>;
function fetchUser(id?: string): Promise<User | null> {
if (id === undefined) return getCurrentUser();
return getUserById(id);
}
// 매 overload mismatch 시 implementation 의 parameter type 매 never 로 narrow.
```
### Mapped type — filter keys
```ts
type FunctionKeys<T> = {
[K in keyof T]: T[K] extends Function ? K : never;
}[keyof T];
class Foo {
x: number = 0;
y: string = '';
greet() {}
fly() {}
}
type Methods = FunctionKeys<Foo>; // 매 'greet' | 'fly'
```
### Empty array literal type
```ts
const empty: never[] = [];
empty.push(1); // 매 type error — never 에 number 할당 X
// 매 generic constraint
function head<T>(arr: readonly T[]): T | never {
if (arr.length === 0) throw new Error();
return arr[0];
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Switch exhaustive | `default: const _: never = x`. |
| Throw helper return type | `: never`. |
| Conditional filter | `T extends U ? T : never`. |
| Impossible field | `field: never` in union member. |
| Generic constraint impossible | `T extends never` (rarely useful). |
**기본값**: 매 exhaustive check 매 `assertNever(x)`. 매 conditional type 의 filter 매 `never` branch.
## 🔗 Graph
- 부모: [[TypeScript]] · [[Type System]]
- 변형: [[unknown]] · [[void]] · [[any]]
- 응용: [[Exhaustive Checking]] · [[Discriminated Unions]] · [[Branded Types for Nominal Typing]]
- Adjacent: [[Conditional Types]] · [[Mapped Types]] · [[as const]]
## 🤖 LLM 활용
**언제**: 매 exhaustive switch enforcement, throw helper, conditional type filter, impossible state encoding 의.
**언제 X**: 매 simple optional (`T | undefined`) — never 매 overkill, 매 runtime null check 가 더 명확한 case.
## ❌ 안티패턴
- **`x: never` 의 value 할당 시도**: 매 `const x: never = 1` 매 항상 error. 매 type-only.
- **never[] 의 push**: 매 element 추가 X — 매 generic 으로 풀어야.
- **catch (e) 매 never 가정**: 매 TS 4.4+ 의 catch 매 default unknown — never 아님.
- **Promise<never>**: 매 reject-only Promise 의 type 으로 의도 — 매 사실은 `Promise<unknown>` 또는 throw helper 가 더 명확.
- **assertNever 없는 default**: 매 switch default 가 그냥 `return` — 매 case 추가 시 silent miss.
## 🧪 검증 / 중복
- Verified (TypeScript Handbook, TS deep dive, Anders Hejlsberg talks).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — never type patterns, exhaustive check, conditional filter, branded types 추가 |