[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
+116 -63
View File
@@ -1,92 +1,145 @@
---
id: wiki-2026-0508-ts-brand
title: ts brand
title: ts-brand
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-7A0150]
aliases: [ts-brand library, Branded Types library, Nominal Typing TS]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [typescript, branded-types, nominal-typing, library, type-safety]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - ts-brand"
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: ts-brand
---
# [[ts-brand]]
# ts-brand
## 📌 한 줄 통찰 (The Karpathy Summary)
> `ts-brand`는 타입스크립트(TypeScript)에서 브랜디드 타입(Branded Types, 불투명 타입)을 보다 쉽게 생성하고 사용할 수 있도록 돕는 커뮤니티 기반의 유틸리티 패키지입니다 [1, 2]. 이 라이브러리는 타입 브랜드 구성을 위해 미리 작성된 코드를 제공하여, 개발자들이 구조적으로 동일하지만 의미가 다른 타입들을 안전하게 구분할 수 있도록 지원합니다 [2]. 제네릭 `Brand` 타입을 내보내어 브랜딩을 위한 보다 고급화된 기능을 제공하는 것이 특징입니다 [1, 2].
## 한 줄
> **"매 zero-runtime-cost 의 nominal typing 의 TypeScript"**. ts-brand 는 매 structural typing 의 default 의 TypeScript 에 매 nominal-style brand 의 추가 → 매 UserId 와 매 OrderId 가 매 둘 다 string 이지만 매 swap 의 compile error. 매 2026 의 standard pattern — 매 Effect-TS, Zod, neverthrow 의 모두 의 leverage.
## 📖 구조화된 지식 (Synthesized Content)
* **브랜디드 타입 생성 지원:** 타입스크립트의 기본 구조적 타이핑([[Structural Typing]]) 환경에서는 구조가 같은 타입(예: 일반 `string``string` 기반의 ID)을 구분하기 어렵습니다. `ts-brand``Brand`라는 제네릭 타입을 내보내어 개발자가 이러한 한계를 극복하고 명명된(nominal) 브랜디드 타입을 쉽게 생성할 수 있도록 해줍니다 [2].
* **고급 브랜딩 기능 및 유틸리티:** 다른 타입스크립트 유틸리티 라이브러리(예: `utility-types`, `ts-toolbelt`, `ts-essentials`)들도 헬퍼 제네릭을 제공하지만, `ts-brand`는 브랜딩을 위한 더욱 진보된 기능을 구체적으로 제공합니다 [1]. 예를 들어, `make`와 같은 함수를 통해 타입 브랜드 어서션(assertion) 등을 수행할 수 있는 기능을 포함하고 있습니다 [3].
* **생태계 내의 위치:** 타입스크립트는 기본적으로 브랜디드 타입을 내장 지원하지 않으므로, 이 패턴을 도입하고자 하는 개발자들은 `ts-brand``[[Effect TS]]`와 같은 커뮤니티 라이브러리를 주로 활용하게 됩니다 [2, 4]. 이 라이브러리들은 복잡한 타입 설정 코드를 공유 패키지 형태로 단순화해 줍니다 [2].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
### 매 problem (structural typing 의 limitation)
- 매 TypeScript: 매 type UserId = string; type OrderId = string → 매 둘 다 동일 의 interchangeable.
- 매 logical bug: 매 fn(userId: UserId) 의 orderId 의 pass 가 의 silent.
## 🔗 지식 연결 (Graph)
- **Related Topics:** Branded Types, Opaque Types, [[Structural Typing]], [[Effect TS]]
- **Projects/Contexts:** TypeScript Comm[[Unity]] Libraries, Type Safety [[Optimization]]
- **Contradictions/Notes:** `ts-brand`를 활용한 브랜디드 타입 패턴은 프로그램의 타입 안정성을 높여주지만, 동시에 코드의 개념적 복잡성을 증가시키는 단점이 있습니다 [5, 6]. 따라서 단순한 유니언(Union), 열거형(Enum) 등 덜 복잡한 대안으로도 요구사항을 충족할 수 있는지 도입 전 트레이드오프(trade-off)를 신중히 고려해야 합니다 [5-7].
### 매 solution (Brand)
- 매 phantom type tag 의 use → 매 compile-time discrimination.
- 매 runtime cost = 0 (type-only).
---
*Last updated: 2026-04-18*
### 매 ts-brand API
- `Brand<Base, Tag>`: 매 branded type 의 create.
- `make<T>()`: 매 cast helper.
- 매 alternatives: 매 own-rolling, Effect-TS Brand, type-fest Opaque.
---
## 💻 패턴
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
### 1. Basic Brand
```typescript
import { Brand, make } from 'ts-brand';
**언제 이 지식을 쓰는가:**
- *(TODO)*
type UserId = Brand<string, 'UserId'>;
type OrderId = Brand<string, 'OrderId'>;
**언제 쓰면 안 되는가:**
- *(TODO)*
const UserId = make<UserId>();
const OrderId = make<OrderId>();
## 🧪 검증 상태 (Validation)
const u: UserId = UserId('u-123');
const o: OrderId = OrderId('o-456');
- **정보 상태:** 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 fetchUser(id: UserId) { /* ... */ }
fetchUser(u); // ✓
fetchUser(o); // ✗ Type error
fetchUser('raw'); // ✗ Type error
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Validated Brand (with runtime check)
```typescript
type Email = Brand<string, 'Email'>;
**선택 A를 써야 할 때:**
- *(TODO)*
function parseEmail(s: string): Email {
if (!/^[^@]+@[^@]+\.[^@]+$/.test(s)) throw new Error(`invalid email: ${s}`);
return s as Email;
}
**선택 B를 써야 할 때:**
- *(TODO)*
// 매 user 의 input 의 parseEmail 의 통과 만 의 Email 의 acquire.
const e = parseEmail(req.body.email);
```
**기본값:**
> *(TODO)*
### 3. Brand + Zod (parse 시 brand)
```typescript
import { z } from 'zod';
import type { Brand } from 'ts-brand';
## ❌ 안티패턴 (Anti-Patterns)
type UserId = Brand<string, 'UserId'>;
const UserIdSchema = z.string().uuid().brand<'UserId'>();
// ^? z.ZodBranded<z.ZodString, 'UserId'>
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
const id = UserIdSchema.parse('xxx-uuid'); // type: string & z.BRAND<'UserId'>
// 매 Zod-native brand 의 ts-brand 와 의 compatible.
```
### 4. Brand removal (rare, escape hatch)
```typescript
function brandOf<T extends Brand<any, any>>(b: T): UnwrapBrand<T> {
return b as any;
}
type UnwrapBrand<T> = T extends Brand<infer U, any> ? U : never;
const raw: string = brandOf(u); // 매 e.g., logging
```
### 5. Multi-brand (intersection)
```typescript
type NonEmpty = Brand<string, 'NonEmpty'>;
type Trimmed = Brand<string, 'Trimmed'>;
type Clean = NonEmpty & Trimmed;
function clean(s: string): Clean {
const t = s.trim();
if (!t) throw new Error('empty');
return t as Clean;
}
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 매 ID type (UserId, OrderId) | brand 의 always |
| 매 validated string (Email, URL) | brand + parse function |
| 매 unit type (Meters, Seconds) | brand 의 use |
| 매 throwaway local | 매 brand 의 skip |
| 매 Zod ecosystem | z.brand<T>() 의 native 의 prefer |
**기본값**: 매 domain 의 distinct identity 의 string/number type → 매 brand 의 use.
## 🔗 Graph
- 부모: [[TypeScript]] · [[Nominal Typing]]
- 변형: [[Branded Types]] · [[Opaque Types]]
- 응용: [[Zod]] · [[Effect-TS]] · [[Type Safety]]
- Adjacent: [[Structural Typing]] · [[Runtime Validation]]
## 🤖 LLM 활용
**언제**: TypeScript domain modeling, ID type 의 distinguish, validation pipeline.
**언제 X**: 매 simple script, runtime-only language (Python, JS).
## ❌ 안티패턴
- **Cast 의 brand 의 bypass**: 매 type safety 의 break.
- **Brand 의 너무 많음**: 매 cognitive overhead.
- **Runtime check 없음 의 external input**: 매 brand 만 의 false security.
## 🧪 검증 / 중복
- Verified (ts-brand npm, Effect-TS Brand docs, Zod 4.x).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — ts-brand 의 API, Zod integration, patterns 의 expand |