[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,102 +2,154 @@
id: wiki-2026-0508-구조적-타이핑-structural-typing
title: 구조적 타이핑(Structural Typing)
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-25EFF5]
aliases: [Structural Typing, Duck Typing (static), 구조적 타이핑]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [typescript, type-system, structural-typing, go-interface]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - 구조적 타이핑([[Structural Typing]])"
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/Go
framework: TS 5.x / Go 1.22+
---
# [[구조적 타이핑(Structural Typing)]]
# 구조적 타이핑(Structural Typing)
## 📌 한 줄 통찰 (The Karpathy Summary)
> 구조적 타이핑은 TypeScript 타입 시스템의 근본적인 원칙으로, 타입의 이름이나 명시적 선언이 아닌 객체의 실제 형태(구조)에 기반하여 타입 호환성을 결정하는 방식입니다 [1, 2]. 이는 "만약 어떤 것이 오리처럼 걷고 갉갉거리면 그것은 오리다"라는 '덕 타이핑(Duck Typing)' 개념으로도 불리며, 대상 타입이 요구하는 최소한의 속성과 메서드를 갖추고 있다면 잉여 속성이 있더라도 호환되는 것으로 간주합니다 [1-3]. 이 시스템은 유연성을 제공하지만, 의미론적 구분이 필요한 상황에서는 한계를 보일 수 있어 이를 보완하는 다양한 기법들이 함께 사용됩니다 [4-6].
## 한 줄
> **"매 type compatibility 를 name 이 아닌 shape (members) 으로 판단하는 type system"**. 매 Go interface, TypeScript, OCaml object 가 대표적. 매 nominal 의 정반대 — 매 "if it walks like a duck" 의 static 버전.
## 📖 구조화된 지식 (Synthesized Content)
* **타입 호환성의 기본 규칙:**
구조적 타이핑 하에서 한 타입(`y`)이 다른 타입(`x`)과 호환되려면 `y`가 최소한 `x`가 가진 모든 멤버를 포함하고 있어야 합니다 [1]. 변수 할당 시, 우변의 값이 타겟 타입의 속성을 모두 충족하기만 한다면 다른 잉여 속성을 가지고 있더라도 구조적으로 호환되는 것으로 간주되어 할당이 허용됩니다 [1].
## 매 핵심
* **명목적 타이핑(Nominal Typing)과의 차이:**
Java C#과 같은 전통적인 객체 지향 언어에서 사용하는 명목적 타이핑은 타입의 이름이나 명시적 상속/구현 선언이 일치해야만 호환성이 인정됩니다 [2, 7]. 반면, TypeScript는 객체의 구조(속성과 메서드의 형태)만 일치하면 동일한 타입 혹은 호환 가능한 타입으로 처리하는 유연성을 갖습니다 [2].
### 매 nominal vs structural
- **Nominal** (Java, C#): 매 declared 동일 type / inheritance 만 호환.
- **Structural** (TS, Go interface, OCaml): 매 같은 shape 면 호환 — 매 declaration 무관.
* **과잉 속성 체크([[Excess Property Checking]])를 통한 방어:**
구조적 타이핑의 유연함은 오타(예: `color` 대신 `colour` 입력)를 내거나 의도치 않은 데이터를 전달하는 실수를 유발할 수 있습니다 [8, 9]. 이를 방지하기 위해 TypeScript는 객체 리터럴이 변수에 직접 할당되거나 함수의 인자로 전달될 때 예외적으로 엄격하게 동작하는 '과잉 속성 체크'를 발동시킵니다 [3, 10, 11]. 이를 통해 타겟 인터페이스에 정의되지 않은 잉여 속성이 포함되는 것을 컴파일 시점에 차단합니다 [3, 10].
### 매 TS 의 작동
- 매 interface / type alias 는 매 shape 만 정의.
- 매 assignment / argument 시 매 source 가 target 의 모든 required member 를 가지면 OK.
- 매 extra member 는 OK (단, EPC 는 fresh literal 에서만 차단).
* **구조적 타이핑의 한계와 브랜디드 타입(Branded Types):**
구조적 타이핑은 속성 구조가 동일하면 타입이 같다고 간주하기 때문에, 동일한 구조를 가졌지만 의미가 전혀 다른 데이터(예: IP와 URL, 일반 문자열과 보안 처리된 문자열, 각기 다른 통화 등)를 구별하지 못하는 문제를 야기합니다 [4-6, 12-14]. 이를 극복하기 위해, 런타임에는 존재하지 않지만 컴파일 시점에만 존재하는 고유한 가상의 속성(브랜드)을 타입에 부여하여 명목적 타이핑과 유사한 강력한 격리를 제공하는 브랜디드 타입(또는 Opaque Types) 기법이 사용됩니다 [6, 14-16].
### 매 Go interface 의 implicit satisfaction
- Go 는 매 `implements` 키워드 X — 매 method set 만족 시 자동 satisfy.
* **`satisfies` 연산자의 활용:**
할당 시 중간 변수를 거치면 과잉 속성 체크가 우회되는 구조적 타이핑의 취약점을 보완하기 위해 `satisfies` 연산자를 활용할 수 있습니다 [17-19]. 이 연산자는 객체가 특정 구조를 만족하는지 엄격하게 검사(과잉 속성 방지)하면서도, 할당된 객체 속성의 구체적인 리터럴 타입과 잉여 속성 정보를 그대로 유지하게 해줍니다 [19-21].
### 매 응용
1. Mock / test double 의 trivial implementation.
2. Adapter 의 boilerplate 절감.
3. Library 간 type 의 cross-compat.
4. Type-driven design — 매 minimal interface.
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
## 💻 패턴
## 🔗 지식 연결 (Graph)
- **Related Topics:** [[덕 타이핑(Duck Typing)]], [[명목적 타이핑(Nominal Typing)]], [[과잉 속성 체크(Excess Property Checking)]], 브랜디드 타입(Branded Types), [[satisfies 연산자]]
- **Projects/Contexts:** TypeScript 타입 시스템 아키텍처 및 도메인 기반 설계(DDD)
- **Contradictions/Notes:** 객체 리터럴을 직접 할당하거나 인자로 넘길 때는 예기치 않은 잉여 속성에 대해 엄격한 에러를 발생시키는 반면, 값을 미리 변수에 선언한 뒤 간접적으로 할당할 때는 최소 요건만 충족하면 잉여 속성을 무시하고 할당을 허용하는 동작 방식의 차이가 존재합니다 [8, 10, 17, 18].
---
*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
### TS structural compatibility
```typescript
interface Named { name: string }
class Cat { name = "Tom"; meow() {} }
const x: Named = new Cat(); // ✅ Cat 이 Named 를 implements 선언 X 이지만 OK
```
## 🤔 의사결정 기준 (Decision Criteria)
### TS interface vs nominal-like brand
```typescript
// 매 nominal-style (brand)
type Email = string & { __brand: "Email" };
type UserId = string & { __brand: "UserId" };
**선택 A를 써야 할 때:**
- *(TODO)*
const e: Email = "a@b.com" as Email;
const u: UserId = e; // ❌ brand mismatch — 매 nominal-like 차단
```
**선택 B를 써야 할 때:**
- *(TODO)*
### Go interface 의 implicit satisfy
```go
type Reader interface { Read(p []byte) (int, error) }
**기본값:**
> *(TODO)*
type FileR struct{ /* ... */ }
func (f *FileR) Read(p []byte) (int, error) { /* ... */ return 0, nil }
## ❌ 안티패턴 (Anti-Patterns)
var r Reader = &FileR{} // ✅ implements 선언 없음 — 매 method 매 충족
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### Duck-typing function
```typescript
function logName(x: { name: string }) {
console.log(x.name);
}
logName({ name: "A", age: 1 }); // ✅ extra OK — fresh 시 EPC 발동 가능
const obj = { name: "A", age: 1 };
logName(obj); // ✅ 매 EPC 비활성
```
### 매 minimal interface principle (Go)
```go
// ❌ huge interface
// type Storage interface { Save, Load, Delete, List, ... }
// ✅ 매 small interface, compose by need
type Saver interface { Save(k string, v []byte) error }
type Loader interface { Load(k string) ([]byte, error) }
// 매 caller 가 필요한 것만 require
```
### Type narrowing via shape (TS)
```typescript
function area(s: { kind: "circle"; r: number } | { kind: "rect"; w: number; h: number }) {
if (s.kind === "circle") return Math.PI * s.r * s.r; // shape narrowed
return s.w * s.h;
}
```
### 매 over-structural 의 safety hole
```typescript
interface Meter { value: number }
interface Foot { value: number }
const m: Meter = { value: 5 };
const f: Foot = m; // ✅ 매 structural — 매 meter/foot mix-up — 매 brand 로 막아라
```
### satisfies + structural (TS 4.9+)
```typescript
const config = {
port: 8080,
host: "localhost"
} satisfies { port: number; host: string };
// 매 structural compat 확인 + 매 narrow type 유지 + EPC 발동
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 mocking / testing | structural — 매 trivial fake |
| 매 minimal coupling | minimal interface (Go style) |
| 매 unit safety (Email vs UserId) | brand / nominal-emulation |
| 매 cross-library | structural compat |
| 매 enum / discriminator | tagged union (kind: "...") |
**기본값**: 매 TS / Go 의 structural 활용 + 매 unit safety 가 필요한 곳만 brand. 매 모든 type 의 brand 의 X.
## 🔗 Graph
- 부모: [[Type Systems]]
- 변형: [[Nominal Typing]] · [[Duck Typing]] · [[Row Polymorphism]]
- 응용: [[TypeScript]] · [[Go Interface]] · [[OCaml Object]]
- Adjacent: [[과잉 속성 체크 (Excess Property Checking)]] · [[Branded Type]] · [[Discriminated Union]]
## 🤖 LLM 활용
**언제**: type design review, interface 의 minimization, structural mismatch 디버깅.
**언제 X**: 매 runtime type check — 매 structural 은 compile-time only.
## ❌ 안티패턴
- **Big interface (fat interface)**: 매 caller 의 dependency surface 폭증.
- **Unit confusion**: 매 Meter / Foot / UserId / OrderId 의 swap silent — 매 brand 필수.
- **Structural 의 implicit reliance**: 매 refactor 시 silent breakage — 매 explicit type annotation 권장.
## 🧪 검증 / 중복
- Verified (TypeScript Handbook, Pierce *Types and Programming Languages* 2002, Go Spec).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — TS + Go structural + brand + minimal interface |