💻 Programming

Effect

A functional programming library for TypeScript

📖 Detailed Explanation

Effect is a next-generation functional programming library for TypeScript that manages side effects in a type-safe way. Designed with inspiration from Scala's ZIO, it lets you track error handling, concurrency, and resource management at the type-system level.

Effect's core concept is the Effect<Success, Error, Requirements> type. This type expresses, in the type itself, the value returned on success, the possible error types, and the required dependencies. Missing error handling can be detected at compile time, greatly reducing runtime exceptions.

Effect was designed to overcome the limitations of Promise. A Promise does not track error types and executes eagerly, whereas an Effect executes lazily and fully tracks error types. It also provides production-ready features such as cancellation, retries, timeouts, and concurrency control out of the box.

In practice, Effect is especially powerful for complex backend logic, API integration, and building data pipelines. Dependency injection (DI) is built into the type system, making testing easy, and the Schema module lets you handle runtime data validation in a type-safe way as well.

💻 Code Example

import { Effect, pipe, Console } from "effect"

// 1. 기본 Effect 생성과 에러 핸들링
const fetchUser = (id: number): Effect.Effect<User, HttpError> =>
    Effect.tryPromise({
        try: () => fetch(`/api/users/${id}`).then(r => r.json()),
        catch: () => new HttpError("사용자 조회 실패")
    })

// 2. 타입 안전한 에러 처리
const program = pipe(
    fetchUser(1),
    Effect.flatMap(user =>
        Effect.succeed(`환영합니다, ${user.name}님!`)
    ),
    Effect.catchTag("HttpError", (error) =>
        Effect.succeed("게스트로 접속합니다")
    )
)

// 3. 동시성 처리 - 여러 API 병렬 호출
const fetchAllData = Effect.all([
    fetchUser(1),
    fetchPosts(1),
    fetchComments(1)
], { concurrency: 3 }) // 최대 3개 동시 실행

// 4. 재시도 및 타임아웃 설정
const resilientFetch = pipe(
    fetchUser(1),
    Effect.retry({ times: 3 }),           // 최대 3회 재시도
    Effect.timeout("5 seconds"),          // 5초 타임아웃
    Effect.tap(user =>
        Console.log(`사용자: ${user.name}`)
    )
)

// 5. 의존성 주입 (서비스 레이어 패턴)
class Database extends Effect.Tag("Database")<
    Database,
    { query: (sql: string) => Effect.Effect<any[], DbError> }
>() {}

const getUsers = Database.pipe(
    Effect.flatMap(db => db.query("SELECT * FROM users"))
)

// 실행
Effect.runPromise(program).then(console.log)

🗣️ Say It Like This in Practice

💬 In a Meeting
"This service has a lot of external API integrations, so I think we should implement it with Effect. Error types can be tracked at compile time, and retry logic and timeouts can be handled declaratively. It becomes much easier to maintain than Promise chaining."
💬 In an Interview
"Effect is a functional library that tracks errors and dependencies at the type level. In the Effect<A, E, R> type, A is the success value, E is the error type, and R is the required services. This lets you implement the 'Railway Oriented Programming' pattern in TypeScript in a type-safe way."
💬 In a code review
"Here, if you use Effect.runPromiseExit instead of Effect.runPromise, you can receive the result as an Exit type even when an error occurs. And if you use catchTag rather than catchAll, you can selectively handle only specific errors."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Returning an Effect without running it

Effect is lazy, so merely creating one does nothing. You must run it with Effect.runPromise or Effect.runSync. This is a mistake that is often missed in unit tests.

❌
Trying method chaining without pipe

Effect's functions are designed in a pipeline style. Instead of `effect.map(fn)`, you must use `pipe(effect, Effect.map(fn))` or `effect.pipe(Effect.map(fn))`.

✅
Gradual adoption recommended

Effect has a learning curve, so don't migrate the entire codebase at once. Start with new features or complex asynchronous logic, and expand gradually as the team's understanding grows.

🔗 Related Terms

📚 Learn More