[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,91 +2,190 @@
id: wiki-2026-0508-as-const-assertion
title: as const Assertion
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-CAF879]
aliases: [const assertion, const context, readonly literal]
duplicate_of: none
source_trust_level: A
confidence_score: 0.95
tags: [uncategorized]
verification_status: applied
tags: [typescript, type-system, literal-types, immutability]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Mega Batch 2 - Wikified [[as const]] Assertion"
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.x
---
# [[as const Assertion]]
# as const Assertion
## 📌 한 줄 통찰 (The Karpathy Summary)
> `as const` Assertion은 TypeScript에서 값을 깊은 읽기 전용(deeply [[readonly]]) 상태로 만들고 타입을 해당 리터럴 값으로 좁히는(narrow) 기능입니다 [1]. 이를 통해 객체나 배열이 변경되지 않도록 컴파일 타임에 보장하며, 더 정확한 타입 추론을 가능하게 합니다 [1, 2]. 주로 절대 변경되어서는 안 되는 구성(configuration) 객체나 조회 테이블(lookup tables)을 정의할 때 유용하게 사용됩니다 [2].
## 한 줄
> **"매 widening을 끄는 가장 강력한 단언"**. TypeScript 3.4에 등장한 `as const`는 literal type을 보존하면서 모든 property를 `readonly`로 만든다. 매 modern TS 코드의 type-safety 핵심 도구.
## 📖 구조화된 지식 (Synthesized Content)
- **깊은 읽기 전용 및 리터럴 타입 추론:** `as const` 단언은 변수의 타입을 넓은 범위의 원시 타입(예: `string`) 대신 가장 구체적인 리터럴 타입(예: 구체적인 문자열 값)으로 좁혀줍니다 [1]. 또한 객체나 배열의 모든 속성을 깊은 읽기 전용(`readonly`)으로 만들어, 값이 변경되는 것을 방지합니다 [1].
- **불변성과 안전성 확보:** 이 기능을 사용하면 의도치 않은 값의 변경을 막아 컴파일 타임의 타입 검증과 런타임의 불변성(immutability)을 모두 확보할 수 있습니다 [2].
- **`satisfies` 연산자와의 결합 패턴:** TypeScript에서 `as const``satisfies` 연산자와 결합하여 자주 사용됩니다 [2]. 이 조합은 타입 검증(type validation)과 불변성을 동시에 제공하므로, 변경되어서는 안 되는 설정 객체나 룩업 테이블을 안전하게 생성하는 데 매우 이상적인 패턴으로 평가받습니다 [2, 3].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 지식 자산화 및 기존 네트워크 연동 단계.
- **정책 변화:** Programming & Language 카테고리의 전문성 확보 및 링크 밀도 최적화.
### 매 동작 방식
- 매 literal (string, number, boolean, array, object literal) 을 narrow type 으로 고정
- 매 type widening 방지 — `"hello"``string` 이 X, 매 `"hello"` literal type
- 매 array → readonly tuple 변환
- 매 object → 매 모든 property `readonly` + literal type
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[Readonly]], Literal Types, [[Satisfies [[Opera]]tor]]
- **Projects/Contexts:** Configuration Objects, Lookup Tables
- **Contradictions/Notes:** 제공된 소스에서 `as const`에 대한 단독 설명은 다소 간략하며 정보가 부족한 편이지만, `satisfies` 연산자와 결합할 때 불변의 타입 안전 객체(immutable, type-safe objects)를 생성하는 핵심적인 역할을 한다는 점이 뚜렷하게 강조됩니다 [1-3].
### 매 작동 범위
- 매 literal expression 에만 적용 가능
- 매 변수 / 함수 호출 결과에 매 X
- 매 컴파일 타임 only — 매 runtime 영향 X
---
*Last updated: 2026-04-18*
### 매 응용
1. Discriminated union 의 tag 정의.
2. Const enum 의 modern 대체 (literal object).
3. Tuple type 의 명시적 생성 (router params, fixed-length array).
4. Configuration object 의 immutable 보장.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 1. Widening 방지
```typescript
// 매 widening
const x = "foo"; // type: string (let), "foo" (const)
let y = "foo"; // type: string (always widened)
**언제 이 지식을 쓰는가:**
- *(TODO)*
// 매 as const
const x2 = "foo" as const; // type: "foo"
let y2 = "foo" as const; // type: "foo" — 매 let 도 narrow
**언제 쓰면 안 되는가:**
- *(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
// 매 array
const arr1 = [1, 2, 3]; // number[]
const arr2 = [1, 2, 3] as const; // readonly [1, 2, 3]
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Discriminated Union Tag
```typescript
const ACTIONS = {
INCREMENT: "INCREMENT",
DECREMENT: "DECREMENT",
RESET: "RESET",
} as const;
**선택 A를 써야 할 때:**
- *(TODO)*
type Action =
| { type: typeof ACTIONS.INCREMENT; payload: number }
| { type: typeof ACTIONS.DECREMENT; payload: number }
| { type: typeof ACTIONS.RESET };
**선택 B를 써야 할 때:**
- *(TODO)*
// 매 ACTIONS.INCREMENT 의 type 은 "INCREMENT" — 매 string X
```
**기본값:**
> *(TODO)*
### 3. Const Enum 대체
```typescript
// 매 옛 방식 — const enum (tree-shaking 문제, --isolatedModules 충돌)
const enum Color { Red = "red", Blue = "blue" }
## ❌ 안티패턴 (Anti-Patterns)
// 매 modern 방식 — as const
const Color = {
Red: "red",
Blue: "blue",
} as const;
type Color = typeof Color[keyof typeof Color]; // "red" | "blue"
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 4. Readonly Tuple
```typescript
function useState<T>(initial: T) {
let value = initial;
return [value, (v: T) => { value = v; }] as const;
}
// 매 return type: readonly [T, (v: T) => void]
// 매 destructure 시 정확한 type
const [count, setCount] = useState(0);
```
### 5. 매 Object 의 Deep Readonly
```typescript
const config = {
api: {
baseUrl: "https://api.example.com",
timeout: 5000,
retries: 3,
},
features: ["auth", "billing"],
} as const;
// type:
// {
// readonly api: {
// readonly baseUrl: "https://api.example.com";
// readonly timeout: 5000;
// readonly retries: 3;
// };
// readonly features: readonly ["auth", "billing"];
// }
// config.api.timeout = 1000; // ❌ readonly
```
### 6. 매 Type Extraction
```typescript
const ROLES = ["admin", "user", "guest"] as const;
type Role = typeof ROLES[number]; // "admin" | "user" | "guest"
const HTTP_METHODS = ["GET", "POST", "PUT", "DELETE"] as const;
type HttpMethod = typeof HTTP_METHODS[number];
// 매 사용
function fetchData(method: HttpMethod, url: string) { /* ... */ }
fetchData("GET", "/api"); // ✅
fetchData("PATCH", "/api"); // ❌ Argument of type '"PATCH"' is not assignable
```
### 7. Generic Function 의 Inference
```typescript
function pick<T, K extends keyof T>(obj: T, keys: readonly K[]): Pick<T, K> {
const result = {} as Pick<T, K>;
for (const key of keys) result[key] = obj[key];
return result;
}
const user = { id: 1, name: "Alice", age: 30 };
const subset = pick(user, ["id", "name"] as const);
// 매 as const 없으면: keys 는 string[] 으로 추론 → K = string → 매 fail
// 매 as const 있으면: keys 는 readonly ("id" | "name")[] → K = "id" | "name"
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Magic string / number set | `as const` 객체 + `typeof[keyof typeof]` |
| Discriminated union tag | `as const` 로 literal 보장 |
| Tuple return | 함수 끝에 `as const` |
| Config / constants | 매 `as const` 로 deep readonly |
| Const enum 사용 중 | 매 `as const` 객체로 마이그레이션 |
| Mutable shared state | `as const` X — 매 readonly 가 방해 |
**기본값**: 매 literal data 에는 항상 `as const` 를 시도. 매 widening 이 의도일 때만 제외.
## 🔗 Graph
- 부모: [[TypeScript]] · [[Type Assertions]]
- 변형: [[const Assertion]] · [[satisfies Operator]]
- 응용: [[Discriminated Unions]] · [[Tuple Types]] · [[Literal Types]]
- Adjacent: [[Readonly]] · [[Type Narrowing]] · [[Type Inference]]
## 🤖 LLM 활용
**언제**: 매 fixed set of values (action types, route names, status codes), tuple return, config object 정의 시 사용.
**언제 X**: runtime mutation 필요 시, generic widening 이 의도일 때, 매 single primitive variable (이미 `const` 로 충분).
## ❌ 안티패턴
- **Function call 에 적용**: `fetch() as const` — 매 literal 이 X 라 효과 없음.
- **Mutable interface 와 충돌**: `as const` 객체를 mutable interface 에 assign — 매 readonly mismatch 에러.
- **과도한 nesting**: 매 깊은 readonly 가 매 사용처에서 매 type 좁힘 — 매 trade-off 고려.
- **type 와 value 혼동**: `typeof OBJ` vs `OBJ` — 매 type 추출엔 `typeof`.
## 🧪 검증 / 중복
- Verified (TypeScript 3.4+ release notes, TS Handbook 2025 edition).
- 신뢰도 A.
- 매 [[Const Assertions]] 와 동의어 — 매 같은 기능.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — as const 의 7 패턴 + decision matrix |