[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,97 +2,172 @@
|
||||
id: wiki-2026-0508-satisfies-operator
|
||||
title: Satisfies Operator
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-B08904]
|
||||
aliases: [TS satisfies, satisfies keyword, Type Satisfies]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [typescript, type-system, ts-4.9]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - Satisfies [[Opera|Opera]]tor"
|
||||
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
|
||||
---
|
||||
|
||||
# [[Satisfies Operator|Satisfies Operator]]
|
||||
# Satisfies Operator
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> `satisfies` 연산자는 TypeScript 4.9에 도입된 기능으로, 객체가 특정 타입의 형태를 준수하는지 검증하면서도 해당 객체의 구체적인 타입(리터럴 타입 등)을 넓히지(widening) 않고 그대로 유지하는 역할을 합니다 [1-3]. 기존의 타입 어노테이션(`:`)이 가진 타입 확장 문제와 타입 단언(`as`)이 가진 검증 누락 문제를 동시에 해결하여 엄격한 타입 검사와 정밀한 타입 추론을 모두 제공합니다 [1, 3, 4]. 이를 통해 컴파일 타임에 잉여 속성이나 오타를 잡아내어 코드의 안정성과 예측 가능성을 크게 높여줍니다 [3, 5].
|
||||
## 매 한 줄
|
||||
> **"매 satisfies는 type 을 검증하면서 narrow type 을 보존"**. TS 4.9 (2022) 도입. `as` 와 달리 type assertion 이 아니라 type validation — value 의 inferred (narrow) type 은 그대로 유지하면서 declared shape 만 강제. 2026 기준 config object, route map, palette 같은 record 패턴 의 standard.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **리터럴 타입 보존 및 구체성 유지 (Literal Type Preservation):** 기존의 타입 어노테이션(`:`)을 사용하면 구체적인 리터럴 값이 일반적인 타입(예: `"/about"`이 범용적인 `string`으로)으로 확장(widening)됩니다 [2, 6]. 반면 `satisfies` 연산자는 객체가 인터페이스를 충족하는지 확인하면서도 원래의 리터럴 타입을 잃지 않고 그대로 보존하여, 이후 코드에서 더 정확한 자동 완성과 정밀한 타입 추론을 가능하게 합니다 [2, 3, 6].
|
||||
- **엄격한 타입 검증과 과잉 속성 체크 ([[Excess Property Checking|Excess Property Checking]]):** 변수를 간접적으로 할당할 때 발생할 수 있는 과잉 속성 체크(EPC)의 우회 문제를 해결합니다 [3, 7]. `satisfies`는 대상 타입에 정의된 요구사항을 객체가 충족하는지 즉시 검사하여 오타를 잡아내며, 원치 않는 잉여 속성(Excess Properties)이 할당되는 것을 컴파일 시점에 철저히 차단합니다 [3, 5, 8].
|
||||
- **타입 단언(`as`) 및 어노테이션(`:`)과의 비교:**
|
||||
- **타입 어노테이션(`:`):** 변수의 수명 주기에 대한 제약을 정의하지만, 할당된 값의 타입을 명시된 타입으로 강제 확장시킵니다 [6, 9].
|
||||
- **타입 단언(`as`):** 컴파일러의 타입 검증을 강제로 우회하여 런타임 에러를 유발할 수 있으며, 잉여 속성에 대한 검사를 수행하지 못합니다 [9, 10].
|
||||
- **`satisfies`:** 타입을 확장하지 않으면서도 정확한 형태를 검증하므로, 객체 리터럴의 유효성 검사 및 정밀한 타입 유지가 필요할 때 가장 안전한 대안이 됩니다 [4, 11].
|
||||
- **고급 활용 패턴:**
|
||||
- **불변성 확보:** `[[as const|as const]] satisfies` 형태로 결합하면, 객체의 불변성을 보장하면서(런타임 불변성 및 컴파일 타임 보호) 타입 구조까지 엄격하게 강제할 수 있어 설정(Configuration) 객체나 상수 룩업 테이블 작성에 매우 유용합니다 [12].
|
||||
- **식별 가능한 유니온([[Discriminated Unions|Discriminated Unions]]) 보존:** 유니온 타입에서 판별자(Discriminator) 속성의 리터럴 타입을 그대로 보존하여, 이후 올바른 타입 좁히기(Type Narrowing)가 정상적으로 동작하도록 지원합니다 [13].
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 vs Type Annotation
|
||||
- `const x: T = value` → x 의 type 은 T (widening)
|
||||
- `const x = value satisfies T` → x 의 type 은 inferred narrow type, 단 T 호환 강제
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[Excess Property Checking|Excess Property Checking]], Structural Typing, [[Discriminated Unions|Discriminated Unions]], Type Narrowing
|
||||
- **Projects/Contexts:** 설정 객체(Configuration Objects) 검증, 데이터 매핑 및 변환(Data Mapping & Transformation)
|
||||
- **Contradictions/Notes:** 타입 단언(`as`)은 대상 타입과 근본적으로 호환되지 않는 경우가 아니면 잉여 속성이 포함되어 있어도 타입 검사를 강제하지 않고 통과시켜 조용한 에러(silent errors)를 낳을 수 있지만, `satisfies`는 이를 허용하지 않고 컴파일 타임에 엄격히 잡아냅니다 [10]. 또한, `satisfies`는 본래 추가적인 잉여 속성을 허용하는 특성이 있으나, 만약 추가된 속성의 이름이 대상 타입의 속성 철자와 비슷하여 오타로 의심될 경우에는 잠재적 오류로 간주하고 경고를 발생시킵니다 [2, 14, 15].
|
||||
### 매 vs `as`
|
||||
- `as` 는 unsafe cast (런타임 보장 X)
|
||||
- `satisfies` 는 compile-time validation (값 자체의 narrow type 을 잃지 않음)
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
### 매 응용
|
||||
1. Const palette / theme — literal key 보존.
|
||||
2. Route config — handler signature 검증 + key autocomplete.
|
||||
3. Discriminated union literal — kind 가 narrow string literal 로 유지.
|
||||
|
||||
---
|
||||
## 💻 패턴
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### Palette: widening 방지
|
||||
```typescript
|
||||
type Color = "red" | "green" | "blue" | `#${string}`;
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
const palette = {
|
||||
primary: "red",
|
||||
secondary: "#00ff00",
|
||||
accent: "blue",
|
||||
} satisfies Record<string, Color>;
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(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
|
||||
// palette.primary: "red" (narrow), not Color
|
||||
const r: "red" = palette.primary; // OK
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Route config + handler 검증
|
||||
```typescript
|
||||
type Route = {
|
||||
path: string;
|
||||
handler: (req: Request) => Response | Promise<Response>;
|
||||
};
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const routes = {
|
||||
home: { path: "/", handler: () => new Response("hi") },
|
||||
api: { path: "/api", handler: async (req) => new Response("api") },
|
||||
} satisfies Record<string, Route>;
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// autocomplete on routes.home, routes.api (narrow keys)
|
||||
routes.home.path; // string (narrow "/")
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Const enum-like with literal narrowing
|
||||
```typescript
|
||||
const status = {
|
||||
IDLE: "idle",
|
||||
LOADING: "loading",
|
||||
ERROR: "error",
|
||||
} satisfies Record<string, string>;
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
type Status = (typeof status)[keyof typeof status];
|
||||
// "idle" | "loading" | "error"
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### satisfies + as const combo
|
||||
```typescript
|
||||
const config = {
|
||||
retries: 3,
|
||||
endpoints: ["/a", "/b"],
|
||||
} as const satisfies {
|
||||
retries: number;
|
||||
endpoints: readonly string[];
|
||||
};
|
||||
// config.retries: 3 (literal), config.endpoints: readonly ["/a","/b"]
|
||||
```
|
||||
|
||||
### Discriminated union event map
|
||||
```typescript
|
||||
type Event =
|
||||
| { kind: "click"; x: number; y: number }
|
||||
| { kind: "key"; code: string };
|
||||
|
||||
const events = [
|
||||
{ kind: "click", x: 10, y: 20 },
|
||||
{ kind: "key", code: "Enter" },
|
||||
] satisfies Event[];
|
||||
|
||||
// events[0].x is number; kind narrow to "click"
|
||||
```
|
||||
|
||||
### Generic helper preserving inference
|
||||
```typescript
|
||||
function defineConfig<T extends Record<string, unknown>>(c: T): T {
|
||||
return c;
|
||||
}
|
||||
// Old way — full T preserved but no shape check.
|
||||
|
||||
// satisfies way:
|
||||
const cfg = {
|
||||
port: 3000,
|
||||
host: "localhost",
|
||||
} satisfies { port: number; host: string };
|
||||
// cfg.port: number (not number literal). add `as const` for literal.
|
||||
```
|
||||
|
||||
### Schema-aligned object (zod-like)
|
||||
```typescript
|
||||
type UserSchema = { id: string; name: string; admin?: boolean };
|
||||
|
||||
const seedUser = {
|
||||
id: "u1",
|
||||
name: "Alice",
|
||||
admin: true,
|
||||
} satisfies UserSchema;
|
||||
|
||||
if (seedUser.admin) { /* narrow boolean true */ }
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| value 의 narrow type 보존 + shape 검증 | `satisfies` |
|
||||
| 매 값 의 type widening (기본 동작) | `: T` annotation |
|
||||
| 매 unsafe cast (last resort) | `as T` |
|
||||
| Literal + readonly + shape | `as const satisfies T` |
|
||||
|
||||
**기본값**: shape 검증이 필요하면 `satisfies`. 매 `as` 사용은 minimize.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[TypeScript]] · [[Type System]]
|
||||
- 변형: [[as const]] · [[Type Assertion]] · [[Type Annotation]]
|
||||
- 응용: [[Theme Tokens]] · [[Route Definition]] · [[Config Objects]]
|
||||
- Adjacent: [[Discriminated Union]] · [[Const Assertion]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: Config / palette / route map 작성 시 narrow literal 보존이 필요할 때. 매 schema validation + autocomplete 동시 요구.
|
||||
**언제 X**: Function parameter type (annotation 만으로 충분). 매 simple variable typing.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **`as Record<...>` cast**: 매 unsafe. 매 `satisfies` 가 safer alternative.
|
||||
- **Annotation 으로 narrow loss**: `const x: Record<string, Color> = {...}` → key narrow 소실.
|
||||
- **satisfies + assignment**: `let x = v satisfies T; x = "wrong"` → 매 narrow type 만 강제, 후속 assignment 는 inferred type 기준.
|
||||
- **Pseudo-runtime check**: 매 satisfies 는 compile-time only — runtime validation 은 zod / valibot.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (TypeScript 4.9 release notes, TS handbook).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — satisfies operator full content |
|
||||
|
||||
Reference in New Issue
Block a user