[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
+173 -73
View File
@@ -2,99 +2,199 @@
id: wiki-2026-0508-as-const
title: as const
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-701C2F]
aliases: [as const, const assertion, TypeScript const assertion]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [typescript, types, const-assertion, literal-types]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - as const"
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
---
# [[as const|as const]]
# as const
## 📌 한 줄 통찰 (The Karpathy Summary)
> `as const`는 TypeScript에서 값을 깊은 수준의 읽기 전용(deeply [[readonly|readonly]])으로 만들고, 해당 타입을 구체적인 리터럴 값으로 좁히는(narrows types to their literal values) 데 사용되는 단언(assertion) 문법입니다 [1]. 객체나 배열 등이 변경되지 않도록 컴파일 타임 검증과 런타임 불변성을 동시에 확보할 때 유용하게 쓰입니다 [2]. 특히 구성(configuration) 객체나 룩업 테이블을 정의할 때 다른 연산자와 결합하여 매우 강력하고 안전한 타입 패턴을 형성합니다 [2, 3].
## 한 줄
> **"매 TypeScript 의 const assertion — literal type 으로 widening 차단"**. 매 TS 3.4 (2019) 도입. 매 array → readonly tuple, object → readonly with literal types. 매 enum 대안, discriminated union 의 핵심, type-safe routing/config 의 enabler.
## 📖 구조화된 지식 (Synthesized Content)
* **깊은 읽기 전용 및 리터럴 타입 축소 (Deeply Readonly & Literal Type Narrowing)**
`as const` 단언(assertion)을 사용하면 값은 깊게 읽기 전용(deeply readonly) 상태가 됩니다 [1]. 이와 더불어 TypeScript는 값을 포괄적인 기본 타입(예: `string`이나 `number`)으로 넓히지 않고, 작성된 리터럴 값 자체로 타입을 좁혀서(narrow) 추론합니다 [1].
## 매 핵심
* **`satisfies` 연산자와의 결합 패턴**
`as const``satisfies` 연산자와 결합하여 사용할 때 불변성(immutability)과 타입 검증(type validation)을 동시에 얻을 수 있는 강력한 패턴이 됩니다 [2]. 이 조합은 절대로 변경되어서는 안 되는 설정(configuration) 객체나 룩업 테이블(lookup tables)을 작성할 때 이상적입니다 [2, 4].
### 매 widening behavior
- 매 default: `const x = "hello"` → 매 type `string` (literal type widened).
- 매 wait, `const` 변수는 literal 유지: `const x = "hello"``"hello"`. 매 그러나 object property 는 widened: `{ name: "alice" }``{ name: string }`.
- `as const` 의 효과: 매 모든 nested literal 유지 + readonly + tuple inference.
* **컴파일 타임과 런타임의 안정성 보장**
이러한 단언 패턴을 도입하면 의도치 않은 값의 변경을 방지하는 동시에, 객체가 필수적인 타입 구조와 정확히 일치하도록 유지할 수 있습니다 [2]. 결과적으로 개발자는 컴파일 타임의 철저한 검증과 타입 안전성이 보장된 불변 객체를 얻게 됩니다 [2, 3].
### 매 변환 규칙
- **String/number/boolean literal**: 매 widened type 매 → literal type.
- **Array `[1, 2, 3]`**: 매 `number[]``readonly [1, 2, 3]` (tuple).
- **Object `{ a: 1 }`**: 매 `{ a: number }``{ readonly a: 1 }`.
- **Nested**: 매 deep recursive 적용.
* **기타 사용 맥락**
일반적으로 프론트엔드 환경에서 타입 추론이나 타입 가드를 목적으로 `as const`를 흔히 붙여서 사용해 왔으나, 최신 문법 구조나 패턴 매칭 라이브러리 적용 등을 통해 이러한 `as const` 사용을 제거(대체)할 수 있다는 의견도 존재합니다 [5].
### 매 응용
1. **Discriminated unions**: 매 `kind: "circle" as const` 로 narrow.
2. **Action creators (Redux)**: 매 type 이 literal string 으로 inferred.
3. **Route configs**: 매 path 가 literal string 으로 inferred → type-safe `Link to=`.
4. **Tuple returns**: 매 `return [value, setter] as const` — React custom hook pattern.
5. **enum 대안**: 매 `const Status = { Idle: "idle", Loading: "loading" } as const`.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 💻 패턴
## 🔗 지식 연결 (Graph)
- **Related Topics:** satisfies, [[readonly|readonly]], Literal Types, Type Narrowing
- **Projects/Contexts:** TypeScript 구성(configuration) 객체 및 룩업 테이블 모델링, 불변성(Immutability) 보장 패턴
- **Contradictions/Notes:** 소스 상에 명시적인 모순은 없으나, 타입 추론과 타입 가드를 위해 관행적으로 `as const`를 붙여 쓰던 것을 특정 패턴 도입을 통해 생략할 수도 있다는 개발자 커뮤니티의 코멘트가 존재합니다 [5].
### Tuple return — custom hook
```ts
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn(o => !o), []);
return [on, toggle] as const;
// 매 type: readonly [boolean, () => void]
// 매 without `as const`: (boolean | (() => void))[] — useless union
}
---
*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
const [isOpen, toggle] = useToggle(); // 매 properly typed
```
## 🤔 의사결정 기준 (Decision Criteria)
### Discriminated union via const
```ts
const success = (data: string) => ({ kind: "success", data } as const);
const error = (msg: string) => ({ kind: "error", msg } as const);
**선택 A를 써야 할 때:**
- *(TODO)*
type Result = ReturnType<typeof success> | ReturnType<typeof error>;
// { readonly kind: "success"; readonly data: string }
// | { readonly kind: "error"; readonly msg: string }
**선택 B를 써야 할 때:**
- *(TODO)*
function handle(r: Result) {
if (r.kind === "success") {
r.data; // string
} else {
r.msg; // string
}
}
```
**기본값:**
> *(TODO)*
### Enum 대안 (lighter, tree-shakeable)
```ts
const Status = {
Idle: "idle",
Loading: "loading",
Success: "success",
Error: "error",
} as const;
## ❌ 안티패턴 (Anti-Patterns)
type Status = typeof Status[keyof typeof Status];
// 매 "idle" | "loading" | "success" | "error"
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
function setStatus(s: Status) { /* ... */ }
setStatus(Status.Loading); // ok
setStatus("loading"); // ok — literal type
setStatus("invalid"); // 매 type error
```
### Type-safe config / route table
```ts
const routes = {
home: "/",
user: "/user/:id",
settings: "/settings",
} as const;
type RouteKey = keyof typeof routes;
type RoutePath = typeof routes[RouteKey];
// 매 "/" | "/user/:id" | "/settings"
function Link<K extends RouteKey>({ to }: { to: K }) {
return <a href={routes[to]}>...</a>;
}
```
### Array of literals → union
```ts
const SIZES = ["sm", "md", "lg", "xl"] as const;
type Size = typeof SIZES[number];
// 매 "sm" | "md" | "lg" | "xl"
function Button({ size }: { size: Size }) { /* */ }
// 매 runtime + type 동시 derive — 매 single source of truth.
SIZES.forEach(s => console.log(s)); // runtime iterable
```
### Action creators (Redux Toolkit 이전 패턴)
```ts
const incrementAction = (n: number) => ({
type: "counter/increment",
payload: n,
} as const);
type IncrementAction = ReturnType<typeof incrementAction>;
// { readonly type: "counter/increment"; readonly payload: number }
```
### Deep readonly via as const
```ts
const config = {
api: {
baseUrl: "https://api.example.com",
timeout: 5000,
},
features: ["auth", "billing"],
} as const;
config.api.baseUrl = "..."; // 매 error: readonly
config.features.push("new"); // 매 error: readonly
config.api.baseUrl; // type: "https://api.example.com" (literal)
```
### satisfies + as const (TS 4.9+)
```ts
const palette = {
red: "#ff0000",
blue: "#0000ff",
green: "#00ff00",
} as const satisfies Record<string, `#${string}`>;
palette.red; // type: "#ff0000" — literal preserved
// 매 satisfies validates shape, as const preserves literals.
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Custom hook tuple return | `as const` 필수. |
| Enum 대체 | `as const` object + `typeof[keyof]`. |
| Config / route table | `as const` + `satisfies` (TS 4.9+). |
| Discriminated union | `kind: "x" as const` literal narrow. |
| Mutable runtime data | 매 `as const` 사용 X — readonly 가 방해. |
**기본값**: 매 const literal 유지 필요 시 `as const`. 매 type validation 까지 매 `as const satisfies`.
## 🔗 Graph
- 부모: [[TypeScript]] · [[Type System]]
- 변형: [[Satisfies Operator]] · [[Readonly]] · [[Tuple Types]]
- 응용: [[Discriminated Unions]] · [[Custom Hooks]] · [[Redux Toolkit]]
- Adjacent: [[Literal Types]] · [[Type Widening]] · [[Branded Types for Nominal Typing]]
## 🤖 LLM 활용
**언제**: custom hook tuple return, enum 대체, action creator, route/config table 의 type-safety, discriminated union narrowing 의.
**언제 X**: 매 mutable 한 runtime data (readonly 가 방해), 매 simple primitive 의 (`const x = 1` 매 already literal).
## ❌ 안티패턴
- **`as` cast 와 혼동**: 매 `as const` 매 special — `as Foo` (type assertion) 와 다름.
- **Mutable assumption**: 매 `as const` array 매 readonly — `.push()` X. `[...arr]` spread 후 mutate.
- **Object 의 partial as const**: 매 nested object 의 일부만 const 의도 — 매 not possible. 매 전체 deep 매 readonly.
- **enum + as const 동시**: 매 redundant. enum 자체로 literal type.
- **JSON.stringify 의 사용**: 매 JSON 화하면 readonly 손실 — runtime 에서 의미 없음.
## 🧪 검증 / 중복
- Verified (TypeScript Handbook, TS 3.4 release notes).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — const assertion patterns, enum 대안, discriminated union, satisfies combo 추가 |