[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,98 +1,229 @@
|
||||
---
|
||||
id: wiki-2026-0508-effect-ts-및-ts-brand-라이브러리-활용
|
||||
title: Effect TS 및 ts brand 라이브러리 활용
|
||||
title: Effect TS 및 ts-brand 라이브러리 활용
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-Reinforce-AUTO-C0B018]
|
||||
aliases: [Effect-TS, ts-brand, Branded Types, Effect.gen]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.9
|
||||
tags: [auto-reinforced]
|
||||
verification_status: applied
|
||||
tags: [typescript, functional, effect-system, branded-types]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-20
|
||||
github_commit: "[P-Reinforce] Continuous Worker - [[Effect TS|Effect TS]] 및 [[ts-brand|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: Effect
|
||||
---
|
||||
|
||||
# [[Effect TS 및 ts-brand 라이브러리 활용|Effect TS 및 ts-brand 라이브러리 활용]]
|
||||
# Effect TS 및 ts-brand 라이브러리 활용
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> Effect TS와 ts-brand는 TypeScript에서 구조적으로 동일해 보이는 타입들을 서로 구별하기 위해 고안된 '브랜드 타입(Branded Types)' 패턴의 적용을 돕는 인기 있는 커뮤니티 라이브러리입니다 [1, 2]. TypeScript는 기본적으로 구조적 타이핑([[Structural Typing|Structural Typing]])을 따르지만, 이 라이브러리들을 활용하면 명목적(Nominal) 타이핑과 유사한 안전장치를 마련할 수 있습니다 [2, 3]. 이를 통해 개발자는 단순한 원시 타입(Primitive Type)을 넘어, 비즈니스 규칙이 검증된 안전하고 정교한 타입을 코드 전반에 강제할 수 있습니다 [1, 2].
|
||||
## 매 한 줄
|
||||
> **"매 typed effect system + nominal type 의 — TypeScript 의 의 ZIO/Cats 의 imported"**. Effect 의 의 async/error/dependency 의 의 single 의 `Effect<A, E, R>` 의 의 unify, ts-brand 의 의 structural type 의 의 nominal flavor 의 의 add. 2026 의 매 enterprise TS codebase 의 의 fast 의 emerging.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **ts-brand 라이브러리의 기능과 활용**
|
||||
- `ts-brand`는 타입 브랜드(Type Brands)를 위한 사전 작성된 코드를 제공하여 개발자가 쉽게 브랜디드 타입을 사용할 수 있게 해주는 커뮤니티 패키지입니다 [2].
|
||||
- 브랜딩을 위한 고급 기능을 제공하며 [4], 제네릭 `Brand` 타입을 내보내어 고유한 브랜드 타입들을 생성하는 데 활용됩니다 [2].
|
||||
## 매 핵심
|
||||
|
||||
- **Effect TS 프레임워크의 브랜디드 타입 지원**
|
||||
- Effect는 타입이 풍부한 TypeScript 애플리케이션을 구축하기 위한 범용 프레임워크로, 타입 브랜드를 다루기 위한 전용 `Brand` 유틸리티를 제공합니다 [5].
|
||||
- 주요 유틸리티로 타입 내에서 브랜드 역할을 하는 제네릭 타입인 `Brand.Brand`와, 타입 브랜드 식별 함수를 반환하는 제네릭 함수인 `Brand.nominal`이 있으며, 이 둘을 결합하여 `ts-brand`와 유사한 브랜드 타입을 생성할 수 있습니다 [5].
|
||||
- **단언(Assertion) 함수의 차별화**: `ts-brand`의 `make`와 달리, Effect는 타입 브랜드 단언 함수를 만들기 위해 `Brand.refined`라는 별도의 함수를 제공합니다 [5]. 이 함수는 값이 제약 조건을 충족하는지 판별하는 함수와, 충족하지 않을 경우 에러를 던지는 함수 등 두 가지 매개변수를 받아 작동합니다 [5, 6].
|
||||
- **메타데이터 활용**: Effect TS는 에러 처리나 내부 제어 흐름을 명확히 구분하기 위해 `_tag`와 같은 메타데이터 속성을 활용하는 패턴을 제공하며, 이는 복잡한 로직에서 일관된 에러 처리와 내부 로직 판별을 돕습니다 [7, 8].
|
||||
### 매 Effect 의 type
|
||||
- `Effect<A, E, R>` — 의 success `A`, 의 failure `E`, 의 requirement `R`.
|
||||
- 매 lazy — 매 `Effect.runPromise` / `Effect.runSync` 의 의 actual 의 execute.
|
||||
- 의 composable — `pipe`, `Effect.gen` 의 의 chain.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
|
||||
- **정책 변화:** Programming & Language 분야의 자동 자산화 수행.
|
||||
### 매 ts-brand 의 nominal type
|
||||
- 의 TypeScript structural — `string === string` 의 의 distinguishable X.
|
||||
- Brand 의 의 `string & { __brand: "UserId" }` 의 의 phantom tag.
|
||||
- 의 runtime cost zero — type-level only.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** Branded Types, Opaque Types, Nominal Typing, [[Structural Typing|Structural Typing]]
|
||||
- **Projects/Contexts:** [[TypeScript_Type_Safety|TypeScript Type Safety]]
|
||||
- **Contradictions/Notes:** 두 라이브러리는 모두 타입 안정성을 높이는 데 기여하지만, 타입 브랜드 단언 함수를 다루는 방식에서 차이를 보입니다. `ts-brand`는 `make`를 활용하는 반면, `Effect TS`는 유효성 검사 함수와 에러 처리 함수를 분리하여 입력받는 `Brand.refined`를 사용하도록 설계되었습니다 [5, 6].
|
||||
### 매 응용
|
||||
1. Domain ID (UserId, OrderId 의 의 mix-up 의 prevent).
|
||||
2. Validated value (Email, NonEmptyString).
|
||||
3. Async pipeline 의 typed error.
|
||||
4. Dependency injection (Effect Layer).
|
||||
5. Retry/timeout/concurrency 의 declarative.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-18*
|
||||
## 💻 패턴
|
||||
|
||||
---
|
||||
### ts-brand 기본
|
||||
```ts
|
||||
import type { Brand } from "ts-brand";
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
type UserId = Brand<string, "UserId">;
|
||||
type OrderId = Brand<string, "OrderId">;
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
const makeUserId = (s: string): UserId => s as UserId;
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
function getUser(id: UserId) { /* ... */ }
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
const uid = makeUserId("u_123");
|
||||
const oid = "o_456" as OrderId;
|
||||
|
||||
- **정보 상태:** 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
|
||||
getUser(uid);
|
||||
// getUser(oid); // 매 compile error — UserId 의 X
|
||||
// getUser("u_123"); // 매 compile error — raw string
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Validated brand (smart constructor)
|
||||
```ts
|
||||
type Email = Brand<string, "Email">;
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
function parseEmail(s: string): Email | null {
|
||||
return /^[^@]+@[^@]+\.[^@]+$/.test(s) ? (s as Email) : null;
|
||||
}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
function sendMail(to: Email, subject: string) { /* ... */ }
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
const e = parseEmail(input);
|
||||
if (e) sendMail(e, "hi"); // 매 type-narrowed 의 valid 의 only
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Effect 기본
|
||||
```ts
|
||||
import { Effect, pipe } from "effect";
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
const fetchUser = (id: UserId): Effect.Effect<User, NetworkError | NotFoundError> =>
|
||||
Effect.tryPromise({
|
||||
try: () => fetch(`/api/users/${id}`).then((r) => {
|
||||
if (r.status === 404) throw new NotFoundError(id);
|
||||
return r.json();
|
||||
}),
|
||||
catch: (e) => e instanceof NotFoundError ? e : new NetworkError(e),
|
||||
});
|
||||
|
||||
const program = pipe(
|
||||
fetchUser(uid),
|
||||
Effect.map((u) => u.email),
|
||||
Effect.tap((email) => Effect.log(`Got: ${email}`)),
|
||||
);
|
||||
|
||||
Effect.runPromise(program).then(console.log);
|
||||
```
|
||||
|
||||
### Effect.gen (do-notation)
|
||||
```ts
|
||||
import { Effect } from "effect";
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const user = yield* fetchUser(uid);
|
||||
const orders = yield* fetchOrders(user.id);
|
||||
const valid = orders.filter((o) => o.status === "paid");
|
||||
return { user, orderCount: valid.length };
|
||||
});
|
||||
```
|
||||
|
||||
### Typed retry / timeout
|
||||
```ts
|
||||
import { Effect, Schedule, Duration } from "effect";
|
||||
|
||||
const robust = pipe(
|
||||
fetchUser(uid),
|
||||
Effect.retry(Schedule.exponential(Duration.millis(100)).pipe(Schedule.compose(Schedule.recurs(3)))),
|
||||
Effect.timeout(Duration.seconds(5)),
|
||||
);
|
||||
```
|
||||
|
||||
### Layer / dependency injection
|
||||
```ts
|
||||
import { Context, Effect, Layer } from "effect";
|
||||
|
||||
class Database extends Context.Tag("Database")<Database, {
|
||||
query: (sql: string) => Effect.Effect<unknown[], DBError>;
|
||||
}>() {}
|
||||
|
||||
const DatabaseLive = Layer.succeed(Database, {
|
||||
query: (sql) => Effect.tryPromise({ try: () => pool.query(sql), catch: (e) => new DBError(e) }),
|
||||
});
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const db = yield* Database;
|
||||
const rows = yield* db.query("SELECT * FROM users");
|
||||
return rows;
|
||||
});
|
||||
|
||||
Effect.runPromise(program.pipe(Effect.provide(DatabaseLive)));
|
||||
```
|
||||
|
||||
### Schema (Effect's Zod-equivalent)
|
||||
```ts
|
||||
import { Schema } from "effect";
|
||||
|
||||
const User = Schema.Struct({
|
||||
id: Schema.String.pipe(Schema.brand("UserId")),
|
||||
email: Schema.String.pipe(Schema.pattern(/^[^@]+@[^@]+$/), Schema.brand("Email")),
|
||||
age: Schema.Number.pipe(Schema.int(), Schema.between(0, 150)),
|
||||
});
|
||||
|
||||
type User = Schema.Schema.Type<typeof User>;
|
||||
const decoded = Schema.decodeUnknownSync(User)(input);
|
||||
```
|
||||
|
||||
### 의 Concurrency
|
||||
```ts
|
||||
import { Effect } from "effect";
|
||||
|
||||
const fetchAll = Effect.all(
|
||||
[fetchUser(u1), fetchUser(u2), fetchUser(u3)],
|
||||
{ concurrency: 2 },
|
||||
);
|
||||
```
|
||||
|
||||
### 의 Either (sync error)
|
||||
```ts
|
||||
import { Either } from "effect";
|
||||
|
||||
const safeParse = (s: string): Either.Either<number, "not_a_number"> => {
|
||||
const n = Number(s);
|
||||
return Number.isNaN(n) ? Either.left("not_a_number") : Either.right(n);
|
||||
};
|
||||
```
|
||||
|
||||
### Effect 의 React (effect-rx)
|
||||
```tsx
|
||||
import { useRxSuspense } from "@effect-rx/rx-react";
|
||||
|
||||
const userRx = Rx.make((get) => fetchUser(get(userIdRx)));
|
||||
|
||||
function UserProfile() {
|
||||
const user = useRxSuspense(userRx);
|
||||
return <div>{user.email}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| Domain ID 의 의 mix-up 의 prevent | ts-brand 의만 |
|
||||
| Validated value (email, URL) | ts-brand 의 + smart constructor |
|
||||
| Complex async pipeline | Effect TS |
|
||||
| Typed error + retry + timeout | Effect TS |
|
||||
| DI 의 의 typed | Effect Layer |
|
||||
| Simple fetch + try/catch | 매 plain async — Effect 의 X |
|
||||
|
||||
**기본값**: ts-brand 의 의 always, Effect 의 의 의 complex pipeline 의만.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[TypeScript]] · [[Functional Programming]]
|
||||
- 변형: [[fp-ts]] · [[ZIO]] · [[neverthrow]]
|
||||
- 응용: [[Discriminated Unions for Error Handling]] · [[Dependency Injection]]
|
||||
- Adjacent: [[Zod]] · [[Branded Types]] · [[Schema Validation]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: typed pipeline 의 design, domain ID safety, layer-based DI, schema-driven decode.
|
||||
**언제 X**: 의 매 simple CRUD — 매 Effect 의 learning curve 의 의 not worth.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **`as UserId` 의 의 raw string 의 의 cast**: 의 brand 의 의 bypass — 의 smart constructor 의 의 always.
|
||||
- **Effect 의 의 entire codebase 의 의 force**: 의 team 의 의 buy-in 의 X 의 시 의 — 매 friction.
|
||||
- **`Effect.runSync` 의 의 async 의**: 의 throw 의 의 — runPromise 의 의 사용.
|
||||
- **Mutable state 의 의 Effect 의**: 의 referential transparency 의 의 violation — Ref/Layer 의 의 사용.
|
||||
- **Brand 의 의 nested 의 reuse**: `Brand<Brand<string, "A">, "B">` 의 의 confusing — 매 single brand 의 keep.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Effect-TS docs effect.website, ts-brand npm, ZIO inspiration, Effect Schema docs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — Effect.gen + Layer + Schema + ts-brand smart constructor 추가 |
|
||||
|
||||
Reference in New Issue
Block a user