Effect TypeScript Best Practices
Effect is a TypeScript library for building complex, type-safe applications with structured
error handling, dependency injection via services/layers, fiber-based concurrency, and
resource safety.
When to Apply
- Writing or reviewing TypeScript code that imports from
effect, @effect/schema, or @effect/platform
- Implementing typed error handling with
Effect<Success, Error, Requirements>
- Building services and layers for dependency injection
- Working with Schema for data validation, decoding, and transformation
- Using fiber-based concurrency (queues, semaphores, PubSub, deferred)
- Processing data with Stream and Sink
- Migrating from Promises, fp-ts, neverthrow, or ZIO to Effect
How to Use
This skill is organized by domain. Read the relevant reference file for the area you're working in.
Read First: The Paradigm
Always read this before diving into API references, especially when refactoring existing
code to use Effect or writing new Effect services:
| Reference |
When to Read |
| Think in Effect: The Paradigm Shift |
Before any other reference. Mental model shifts, refactoring recipes, anti-patterns, application architecture. Read this to understand HOW to think in Effect — the other files teach WHAT to type. |
Core Foundations
| Reference |
When to Read |
| Getting Started |
Creating the Effect type, pipelines, generators, running effects |
| Error Management |
Typed errors, recovery, retrying, timeouts, sandboxing |
| Core Concepts |
Request batching, configuration management, runtime system |
Data & Validation
| Reference |
When to Read |
| Data Types |
Option, Either, Cause, Chunk, DateTime, Duration, Exit, Data |
| Schema Basics |
Schema intro, basic usage, classes, constructors, effect data types |
| Schema Advanced |
Transformations, filters, annotations, error formatting, JSON Schema output |
Architecture & Dependencies
| Reference |
When to Read |
| Requirements Management |
Services, Layers, dependency injection, layer memoization |
| Resource Management |
Scope, safe resource acquisition/release, caching |
| State Management |
Ref, SubscriptionRef, SynchronizedRef for concurrent state |
Concurrency & Streaming
| Reference |
When to Read |
| Concurrency |
Fibers, Deferred, Latch, PubSub, Queue, Semaphore |
| Streams and Sinks |
Creating, consuming, transforming streams; sink operations |
| Scheduling |
Built-in schedules, cron, combinators, repetition |
Platform & Observability
| Reference |
When to Read |
| Platform |
FileSystem, Command, Terminal, KeyValueStore, Path |
| Observability |
Logging, metrics, tracing, Supervisor |
| Testing |
TestClock for time simulation; for service mocking and layer testing, see Requirements Management |
Style, AI & Migration
| Reference |
When to Read |
| Code Style |
Branded types, pattern matching, dual APIs, guidelines, traits |
| AI Integration |
Effect AI packages for LLM tool use and execution planning |
| Micro |
Lightweight Effect alternative for smaller bundles |
| Migration Guides |
Coming from Promises, fp-ts, neverthrow, or ZIO |
Quick Reference — Common Patterns
The Effect Type
// ┌─── Success type
// │ ┌─── Error type
// │ │ ┌─── Required dependencies
// ▼ ▼ ▼
Effect<Success, Error, Requirements>
Creating Effects
import { Effect } from "effect"
// From sync values
const succeed = Effect.succeed(42)
const fail = Effect.fail(new Error("oops"))
// From sync code that may throw
const sync = Effect.try(() => JSON.parse(data))
// From promises
const async = Effect.tryPromise(() => fetch(url))
// From generators (recommended for complex flows)
const program = Effect.gen(function* () {
const user = yield* getUser(id)
const todos = yield* getTodos(user.id)
return { user, todos }
})
Running Effects
// Async (returns Promise)
Effect.runPromise(program)
// With full Exit information
Effect.runPromiseExit(program)
// Sync (throws on async)
Effect.runSync(program)
Typed Errors
import { Data, Effect } from "effect"
class NotFound extends Data.TaggedError("NotFound")<{
readonly id: string
}> {}
class Unauthorized extends Data.TaggedError("Unauthorized")<{}> {}
// Error type is tracked: Effect<User, NotFound | Unauthorized>
const getUser = (id: string) =>
Effect.gen(function* () {
// ...
})
Services and Layers
import { Context, Effect, Layer } from "effect"
// Define a service
class UserRepo extends Context.Tag("UserRepo")<
UserRepo,
{ readonly findById: (id: string) => Effect.Effect<User, NotFound> }
>() {}
// Use in effects — adds to Requirements channel
const program = Effect.gen(function* () {
const repo = yield* UserRepo
return yield* repo.findById("1")
})
// Implement with a Layer
const UserRepoLive = Layer.succeed(UserRepo, {
findById: (id) => Effect.succeed({ id, name: "Alice" })
})
// Provide and run
program.pipe(Effect.provide(UserRepoLive), Effect.runPromise)
Schema Validation
import { Schema } from "effect"
const User = Schema.Struct({
id: Schema.Number,
name: Schema.String,
email: Schema.String.pipe(Schema.pattern(/@/))
})
type User = typeof User.Type
// Decode (parse + validate)
const decode = Schema.decodeUnknownSync(User)
const user = decode({ id: 1, name: "Alice", email: "a@b.com" })
Pipelines
import { Effect, pipe } from "effect"
// Data-last (pipe style)
const result = pipe(
getTodos,
Effect.map((todos) => todos.filter((t) => !t.done)),
Effect.flatMap((active) => sendNotification(active.length)),
Effect.catchTag("NetworkError", () => Effect.succeed("offline"))
)
// Fluent (method style)
const result2 = getTodos.pipe(
Effect.map((todos) => todos.filter((t) => !t.done)),
Effect.flatMap((active) => sendNotification(active.length))
)
Gotchas
See gotchas.md for known failure points.
1---2name: effect-ts3description: Effect-TS library usage in TypeScript — Effect.gen generators, Schema.Struct/Schema.Class definitions, Layer/Context.Tag/Service patterns, Effect.pipe pipelines, Data.TaggedError/Data.Class error types, Ref/Queue/PubSub/Deferred concurrency primitives, Match module, Config providers, Scope/Exit/Cause/Runtime patterns, or any code using Effect's typed error channel (E parameter). Trigger when writing, reviewing, debugging, or refactoring TypeScript code that uses Effect — when you see imports from `effect`, `effect/*`, or any `@effect/*` scoped package (schema, platform, sql, opentelemetry, cli, cluster, rpc, vitest). Also trigger when the user asks about Effect patterns, migration from Promises/fp-ts/neverthrow to Effect, or how to structure an Effect application. Do NOT trigger for React's useEffect, Redux side effects, or general English usage of "effect" unless the context clearly involves the Effect-TS library.4---5# Effect TypeScript Best Practices
6
7Effect is a TypeScript library for building complex, type-safe applications with structured
8error handling, dependency injection via services/layers, fiber-based concurrency, and
9resource safety.
10
11## When to Apply
12
13- Writing or reviewing TypeScript code that imports from `effect`, `@effect/schema`, or `@effect/platform`
14- Implementing typed error handling with `Effect<Success, Error, Requirements>`
15- Building services and layers for dependency injection
16- Working with Schema for data validation, decoding, and transformation
17- Using fiber-based concurrency (queues, semaphores, PubSub, deferred)
18- Processing data with Stream and Sink
19- Migrating from Promises, fp-ts, neverthrow, or ZIO to Effect
20
21## How to Use
22
23This skill is organized by domain. Read the relevant reference file for the area you're working in.
24
25### Read First: The Paradigm
26
27**Always read this before diving into API references**, especially when refactoring existing
28code to use Effect or writing new Effect services:
29
30| Reference | When to Read |
31|-----------|-------------|
32| [**Think in Effect: The Paradigm Shift**](references/getting-paradigm.md) | **Before any other reference.** Mental model shifts, refactoring recipes, anti-patterns, application architecture. Read this to understand HOW to think in Effect — the other files teach WHAT to type. |
33
34### Core Foundations
35
36| Reference | When to Read |
37|-----------|-------------|
38| [Getting Started](references/getting-started.md) | Creating the Effect type, pipelines, generators, running effects |
39| [Error Management](references/error-management.md) | Typed errors, recovery, retrying, timeouts, sandboxing |
40| [Core Concepts](references/core-concepts.md) | Request batching, configuration management, runtime system |
41
42### Data & Validation
43
44| Reference | When to Read |
45|-----------|-------------|
46| [Data Types](references/data-types.md) | Option, Either, Cause, Chunk, DateTime, Duration, Exit, Data |
47| [Schema Basics](references/schema-basics.md) | Schema intro, basic usage, classes, constructors, effect data types |
48| [Schema Advanced](references/schema-advanced.md) | Transformations, filters, annotations, error formatting, JSON Schema output |
49
50### Architecture & Dependencies
51
52| Reference | When to Read |
53|-----------|-------------|
54| [Requirements Management](references/req-management.md) | Services, Layers, dependency injection, layer memoization |
55| [Resource Management](references/resource-management.md) | Scope, safe resource acquisition/release, caching |
56| [State Management](references/state-management.md) | Ref, SubscriptionRef, SynchronizedRef for concurrent state |
57
58### Concurrency & Streaming
59
60| Reference | When to Read |
61|-----------|-------------|
62| [Concurrency](references/conc-concurrency.md) | Fibers, Deferred, Latch, PubSub, Queue, Semaphore |
63| [Streams and Sinks](references/streams-and-sinks.md) | Creating, consuming, transforming streams; sink operations |
64| [Scheduling](references/sched-scheduling.md) | Built-in schedules, cron, combinators, repetition |
65
66### Platform & Observability
67
68| Reference | When to Read |
69|-----------|-------------|
70| [Platform](references/plat-platform.md) | FileSystem, Command, Terminal, KeyValueStore, Path |
71| [Observability](references/obs-observability.md) | Logging, metrics, tracing, Supervisor |
72| [Testing](references/test-testing.md) | TestClock for time simulation; for service mocking and layer testing, see [Requirements Management](references/req-management.md) |
73
74### Style, AI & Migration
75
76| Reference | When to Read |
77|-----------|-------------|
78| [Code Style](references/code-style.md) | Branded types, pattern matching, dual APIs, guidelines, traits |
79| [AI Integration](references/ai-integration.md) | Effect AI packages for LLM tool use and execution planning |
80| [Micro](references/micro-module.md) | Lightweight Effect alternative for smaller bundles |
81| [Migration Guides](references/migration-guides.md) | Coming from Promises, fp-ts, neverthrow, or ZIO |
82
83## Quick Reference — Common Patterns
84
85### The Effect Type
86```ts
87// ┌─── Success type
88// │ ┌─── Error type
89// │ │ ┌─── Required dependencies
90// ▼ ▼ ▼
91Effect<Success, Error, Requirements>
92```
93
94### Creating Effects
95```ts
96import { Effect } from "effect"
97
98// From sync values
99const succeed = Effect.succeed(42)
100const fail = Effect.fail(new Error("oops"))
101
102// From sync code that may throw
103const sync = Effect.try(() => JSON.parse(data))
104
105// From promises
106const async = Effect.tryPromise(() => fetch(url))
107
108// From generators (recommended for complex flows)
109const program = Effect.gen(function* () {
110 const user = yield* getUser(id)
111 const todos = yield* getTodos(user.id)
112 return { user, todos }
113})
114```
115
116### Running Effects
117```ts
118// Async (returns Promise)
119Effect.runPromise(program)
120
121// With full Exit information
122Effect.runPromiseExit(program)
123
124// Sync (throws on async)
125Effect.runSync(program)
126```
127
128### Typed Errors
129```ts
130import { Data, Effect } from "effect"
131
132class NotFound extends Data.TaggedError("NotFound")<{
133 readonly id: string
134}> {}
135
136class Unauthorized extends Data.TaggedError("Unauthorized")<{}> {}
137
138// Error type is tracked: Effect<User, NotFound | Unauthorized>
139const getUser = (id: string) =>
140 Effect.gen(function* () {
141 // ...
142 })
143```
144
145### Services and Layers
146```ts
147import { Context, Effect, Layer } from "effect"
148
149// Define a service
150class UserRepo extends Context.Tag("UserRepo")<
151 UserRepo,
152 { readonly findById: (id: string) => Effect.Effect<User, NotFound> }
153>() {}
154
155// Use in effects — adds to Requirements channel
156const program = Effect.gen(function* () {
157 const repo = yield* UserRepo
158 return yield* repo.findById("1")
159})
160
161// Implement with a Layer
162const UserRepoLive = Layer.succeed(UserRepo, {
163 findById: (id) => Effect.succeed({ id, name: "Alice" })
164})
165
166// Provide and run
167program.pipe(Effect.provide(UserRepoLive), Effect.runPromise)
168```
169
170### Schema Validation
171```ts
172import { Schema } from "effect"
173
174const User = Schema.Struct({
175 id: Schema.Number,
176 name: Schema.String,
177 email: Schema.String.pipe(Schema.pattern(/@/))
178})
179
180type User = typeof User.Type
181
182// Decode (parse + validate)
183const decode = Schema.decodeUnknownSync(User)
184const user = decode({ id: 1, name: "Alice", email: "a@b.com" })
185```
186
187### Pipelines
188```ts
189import { Effect, pipe } from "effect"
190
191// Data-last (pipe style)
192const result = pipe(
193 getTodos,
194 Effect.map((todos) => todos.filter((t) => !t.done)),
195 Effect.flatMap((active) => sendNotification(active.length)),
196 Effect.catchTag("NetworkError", () => Effect.succeed("offline"))
197)
198
199// Fluent (method style)
200const result2 = getTodos.pipe(
201 Effect.map((todos) => todos.filter((t) => !t.done)),
202 Effect.flatMap((active) => sendNotification(active.length))
203)
204```
205
206## Gotchas
207
208See [gotchas.md](gotchas.md) for known failure points.