Files
2nd/10_Wiki/Topics/Programming & Language/Effect TS.md
T
2026-05-10 22:08:15 +09:00

171 lines
4.7 KiB
Markdown

---
id: wiki-2026-0508-effect-ts
title: Effect TS
category: 10_Wiki/Topics
status: verified
canonical_id: self
aliases: [Effect, Effect-TS, effect.ts]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
verification_status: applied
tags: [typescript, functional-programming, effect, error-handling]
raw_sources: []
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: TypeScript
framework: Effect
---
# Effect TS
## 매 한 줄
> **"매 TypeScript 의 functional effect system — error · concurrency · resource 매 type-level encoding"**. 매 ZIO (Scala) inspired library 의 TS port. 2026 시점 v3.x stable, Discord · Vercel · Stripe internal services 가 production 채택.
## 매 핵심
### 매 Effect<A, E, R>
- `A`: success value type
- `E`: error type (typed errors, no exceptions)
- `R`: required services (DI context)
- 매 lazy description — execution은 `Effect.runPromise` 시점.
### 매 핵심 primitives
- `Effect.succeed` / `Effect.fail` / `Effect.sync` / `Effect.tryPromise`
- `Effect.gen` (generator-based do-notation)
- `Effect.all` (parallel), `Effect.forEach` (concurrency control)
- `Layer` (DI composition), `Context.Tag` (service identity)
### 매 응용
1. API gateway error contracts (`HttpClient` typed errors).
2. Database transactional pipelines (`Effect.scoped` + `Layer`).
3. Streaming ETL (`Stream` module).
## 💻 패턴
### Effect.gen do-notation
```ts
import { Effect } from "effect"
const getUser = (id: string) =>
Effect.gen(function* () {
const db = yield* DatabaseService
const user = yield* db.findUser(id)
if (!user) return yield* Effect.fail(new UserNotFound({ id }))
return user
})
```
### Typed errors (Data.TaggedError)
```ts
import { Data } from "effect"
class UserNotFound extends Data.TaggedError("UserNotFound")<{
id: string
}> {}
class DbConnectionError extends Data.TaggedError("DbConnectionError")<{
cause: unknown
}> {}
```
### Layer composition
```ts
import { Effect, Layer, Context } from "effect"
class DatabaseService extends Context.Tag("DatabaseService")<
DatabaseService,
{ findUser: (id: string) => Effect.Effect<User | null, DbConnectionError> }
>() {}
const DatabaseLive = Layer.succeed(DatabaseService, {
findUser: (id) =>
Effect.tryPromise({
try: () => pgClient.query("SELECT * FROM users WHERE id=$1", [id]),
catch: (cause) => new DbConnectionError({ cause }),
}),
})
```
### Concurrent execution
```ts
const fetchAll = Effect.forEach(
["a", "b", "c"],
(id) => getUser(id),
{ concurrency: 5 }
)
```
### Retry + timeout
```ts
import { Schedule, Duration } from "effect"
const robust = getUser("123").pipe(
Effect.retry(Schedule.exponential(Duration.millis(100)).pipe(
Schedule.compose(Schedule.recurs(3))
)),
Effect.timeout(Duration.seconds(5))
)
```
### Resource scoping
```ts
const program = Effect.scoped(
Effect.gen(function* () {
const file = yield* Effect.acquireRelease(
openFile("data.txt"),
(f) => closeFile(f)
)
return yield* readContent(file)
})
)
```
### Schema validation
```ts
import { Schema } from "effect"
const User = Schema.Struct({
id: Schema.String,
age: Schema.Number.pipe(Schema.int(), Schema.nonNegative()),
})
const parse = Schema.decodeUnknown(User)
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| 단순 CRUD app | plain async/await + zod |
| 복잡한 error taxonomy | Effect (typed errors) |
| Concurrency-heavy pipeline | Effect (Schedule + Stream) |
| Team unfamiliar with FP | neverthrow / fp-ts 시작 |
**기본값**: greenfield TS backend with complex error contracts → Effect 채택. 매 learning curve 높음 — team buy-in 매 우선.
## 🔗 Graph
- 부모: [[Functional Programming]] · [[TypeScript 타입 시스템 및 인터페이스 설계]]
- 변형: [[Result Type]] · [[neverthrow]]
- 응용: [[견고한 도메인 모델 및 API 계약 설계]] · [[API 응답 및 에러 핸들링 아키텍처]]
- Adjacent: [[Zod 런타임 유효성 검사 통합]] · [[ts-brand]]
## 🤖 LLM 활용
**언제**: TS backend with strict error typing, dependency injection at type level, retry/circuit-breaker policies.
**언제 X**: 매 simple script · prototype · React component logic — overhead 매 큼.
## ❌ 안티패턴
- **Effect.runSync everywhere**: 매 sync execution 강제 — async benefit 상실.
- **Fail with strings**: typed `TaggedError` 의 사용해야 매 discriminated handling 가능.
- **Layer.merge spaghetti**: 매 dependency graph 의 명시적 organize.
## 🧪 검증 / 중복
- Verified (effect.website official docs · Effect 3.x release notes 2025).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — Effect 3.x patterns, Layer/Schema/typed errors |