(
field:
| FixedField<Duration.Duration>
| SwappableField<Duration.Duration>,
options?: { readonly fallback?: Duration.Input }
): Layer.Layer<PollingTag>Cadence read from a DynamicConfig field on EVERY tick — swap the field's value (locally or
over a ProcessManager control verb) and the new interval applies from the next wait. When the
field is swappable AND a DynamicConfigStore is in context, the current wait also WAKES on
swap, so a shorter interval takes effect immediately instead of after the old one elapses
(presence-driven, like durability: no store → no subscription, and R stays never).
Read failures fall back to options.fallback when given; otherwise they are defects — a
misconfigured cadence should be loud, not a silent default.
export const const dynamic: (
field:
| FixedField<Duration.Duration>
| SwappableField<Duration.Duration>,
options?: {
readonly fallback?: Duration.Input
}
) => Layer.Layer<PollingTag>
Cadence read from a DynamicConfig field on EVERY tick — swap the field's value (locally or
over a ProcessManager control verb) and the new interval applies from the next wait. When the
field is swappable AND a DynamicConfigStore is in context, the current wait also WAKES on
swap, so a shorter interval takes effect immediately instead of after the old one elapses
(presence-driven, like durability: no store → no subscription, and R stays never).
Read failures fall back to options.fallback when given; otherwise they are defects — a
misconfigured cadence should be loud, not a silent default.
dynamic = (
field: anyfield: import FixedFieldFixedField<import DurationDuration.Duration> | import SwappableFieldSwappableField<import DurationDuration.Duration>,
options: | {
readonly fallback?: Duration.Input
}
| undefined
options?: { readonly fallback?: Duration.Input | undefinedfallback?: import DurationDuration.type Input =
| number
| bigint
| Duration.Duration
| readonly [seconds: number, nanos: number]
| `${number} nano`
| `${number} nanos`
| `${number} micro`
| `${number} micros`
| `${number} milli`
| `${number} millis`
| `${number} second`
| `${number} seconds`
| `${number} minute`
| `${number} minutes`
| `${number} hour`
| `${number} hours`
| `${number} day`
| `${number} days`
| `${number} week`
| `${number} weeks`
| "Infinity"
| "-Infinity"
| Duration.DurationObject
Valid input types that can be converted to a Duration.
When to use
Use when an API should accept any value that Effect can convert into a
Duration, including existing durations, millisecond numbers, nanosecond
bigints, high-resolution tuples, duration strings, infinity strings, or
duration objects.
Details
String inputs accept values like "10 seconds", "500 millis",
"Infinity", and "-Infinity". Finite fractional values that are
normalized to nanoseconds are rounded to the nearest nanosecond, with ties
away from zero.
Input }
): import LayerLayer.interface Layer<in ROut, out E = never, out RIn = never>A Layer describes how to build one or more services for dependency injection.
When to use
Use to model construction of application services for dependency injection,
especially when services have dependencies, can fail during construction, or
need scoped setup and release.
Details
A Layer<ROut, E, RIn> represents ROut as the services this layer
provides, E as the possible errors during layer construction, and RIn as
the services this layer requires as dependencies.
Layer<import PollingTagPollingTag> => {
const const fallback:
| Duration.Duration
| undefined
fallback =
options: | {
readonly fallback?: Duration.Input
}
| undefined
options?.fallback?: Duration.Input | undefinedfallback === var undefinedundefined
? var undefinedundefined
: import DurationDuration.const fromInputUnsafe: (
input: Duration.Input
) => Duration.Duration
Decodes a Duration.Input into a Duration.
When to use
Use when the input has already been validated or comes from a trusted source
and throwing is acceptable for invalid duration syntax.
Gotchas
If the input is not a valid Duration.Input, it throws an error.
Example (Decoding duration inputs)
import { Duration } from "effect"
const duration1 = Duration.fromInputUnsafe(1000) // 1000 milliseconds
const duration2 = Duration.fromInputUnsafe("5 seconds")
const duration3 = Duration.fromInputUnsafe("Infinity")
const duration4 = Duration.fromInputUnsafe([2, 500_000_000]) // 2 seconds and 500ms
fromInputUnsafe(options: {
readonly fallback?: Duration.Input
}
options.fallback?: Duration.Inputfallback);
const const read: Effect.Effect<
Duration.Duration,
never,
never
>
const read: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
read: import EffectEffect.interface Effect<out A, out E = never, out R = never>The Effect interface defines a value that lazily describes a workflow or
job. The workflow requires some context R, and may fail with an error of
type E, or succeed with a value of type A.
When to use
Use when you need to represent a lazy, composable workflow that can require
services, fail with a typed error, or succeed with a typed value.
Details
Effect values model resourceful interaction with the outside world,
including synchronous, asynchronous, concurrent, and parallel interaction.
They use a fiber-based concurrency model, with built-in support for
scheduling, fine-grained interruption, structured concurrency, and high
scalability.
To run an Effect value, you need a Runtime, which is a type that is
capable of executing Effect values.
Effect<import DurationDuration.Duration> = import EffectEffect.catch<Duration.Duration, unknown, never, Duration.Duration, never, never>(self: Effect.Effect<Duration.Duration, unknown, never>, f: (e: unknown) => Effect.Effect<Duration.Duration, never, never>): Effect.Effect<Duration.Duration, never, never> (+1 overload)
export catch
catch(field: anyfield, (error: unknownerror) =>
const fallback:
| Duration.Duration
| undefined
fallback === var undefinedundefined ? import EffectEffect.const die: (
defect: unknown
) => Effect.Effect<never>
Creates an effect that terminates a fiber with a specified error.
When to use
Use when you need an Effect to report an unrecoverable defect instead of a
typed error.
Details
The die function is used to signal a defect, which represents a critical
and unexpected error in the code. When invoked, it produces an effect that
does not handle the error and instead terminates the fiber.
The error channel of the resulting effect is of type never, indicating that
it cannot recover from this failure.
Example (Failing on division by zero)
import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.die(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = divide(1, 0)
Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: Cannot divide by zero
// ...stack trace...
die(error: unknownerror) : import EffectEffect.const succeed: <Duration.Duration>(value: Duration.Duration) => Effect.Effect<Duration.Duration, never, never>Creates an Effect that always succeeds with a given value.
When to use
Use when an effect should complete successfully with a specific value without any errors
or external dependencies.
Example (Creating a successful effect)
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)
succeed(const fallback: Duration.Durationconst fallback: {
value: DurationValue;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
fallback)
);
return import registerPollingLayerregisterPollingLayer(
import LayerLayer.const effect: <unknown, unknown, never, Scope.Scope>(service: Key<unknown, unknown>, effect: Effect.Effect<unknown, never, Scope.Scope>) => Layer.Layer<unknown, never, never> (+1 overload)Constructs a layer from an effect that produces a single service.
When to use
Use when you need to construct a Layer-provided service with an Effect,
dependencies, or scoped resource acquisition.
Details
This allows you to create a Layer from an Effect that produces a service.
The Effect is executed in the scope of the layer, allowing for proper
resource management.
Example (Creating a layer from an effect)
import { Context, Effect, Layer } from "effect"
class Database extends Context.Service<Database, {
readonly query: (sql: string) => Effect.Effect<string>
}>()("Database") {}
const layer = Layer.effect(Database,
Effect.sync(() => ({
query: (sql: string) => Effect.succeed(`Query: ${sql}`)
}))
)
effect(
import PollingTagPollingTag,
import EffectEffect.const gen: <Effect.Effect<Ref.Ref<Deferred.Deferred<void, never>>, never, never> | Effect.Effect<Option.Option<unknown>, never, never> | Effect.Effect<Fiber<void, unknown>, never, Scope.Scope>, PollingService>(f: () => Generator<Effect.Effect<Ref.Ref<Deferred.Deferred<void, never>>, never, never> | Effect.Effect<Option.Option<unknown>, never, never> | Effect.Effect<Fiber<void, unknown>, never, Scope.Scope>, PollingService, never>) => Effect.Effect<PollingService, never, Scope.Scope> (+1 overload)Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to use
Use when you want to write effectful code that looks and behaves like
synchronous code, while still handling asynchronous tasks, errors, and complex
control flow such as loops and conditions.
Generator functions work similarly to async/await but keep errors,
requirements, and interruption in the Effect type. You can yield* values
from effects and return the final result at the end.
Example (Sequencing effects with generators)
import { Data, Effect } from "effect"
class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, DiscountRateError> =>
discountRate === 0
? Effect.fail(new DiscountRateError())
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function*() {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})
gen(function* () {
const const wakeRef: Ref.Ref<
Deferred.Deferred<void, never>
>
const wakeRef: {
ref: MutableRef.MutableRef<A>;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
wakeRef = yield* import RefRef.const make: <Deferred.Deferred<void, never>>(value: Deferred.Deferred<void, never>) => Effect.Effect<Ref.Ref<Deferred.Deferred<void, never>>, never, never>Creates a new Ref with the specified initial value.
When to use
Use to create a Ref for shared mutable state inside an Effect program.
Example (Creating a ref)
import { Effect, Ref } from "effect"
const program = Effect.gen(function*() {
const ref = yield* Ref.make(42)
const value = yield* Ref.get(ref)
console.log(value) // 42
})
make<import DeferredDeferred.interface Deferred<in out A, in out E = never>A Deferred represents an asynchronous variable that can be set exactly
once, with the ability for an arbitrary number of fibers to suspend (by
calling Deferred.await) and automatically resume when the variable is set.
When to use
Use to coordinate multiple fibers around a value or failure that will be
supplied exactly once.
Example (Creating a Deferred for inter-fiber communication)
import { Deferred, Effect, Fiber } from "effect"
// Create and use a Deferred for inter-fiber communication
const program = Effect.gen(function*() {
// Create a Deferred that will hold a string value
const deferred: Deferred.Deferred<string> = yield* Deferred.make<string>()
// Fork a fiber that will set the deferred value
const producer = yield* Effect.forkChild(
Effect.gen(function*() {
yield* Effect.sleep("100 millis")
yield* Deferred.succeed(deferred, "Hello, World!")
})
)
// Fork a fiber that will await the deferred value
const consumer = yield* Effect.forkChild(
Effect.gen(function*() {
const value = yield* Deferred.await(deferred)
console.log("Received:", value)
return value
})
)
// Wait for both fibers to complete
yield* Fiber.join(producer)
const result = yield* Fiber.join(consumer)
return result
})
Companion namespace containing type-level metadata for Deferred.
When to use
Use to reference type-level metadata associated with Deferred.
Deferred<void, never>>(
import DeferredDeferred.const makeUnsafe: <void, never>() => Deferred.Deferred<void, never>Creates an empty Deferred synchronously outside the Effect runtime.
When to use
Use to allocate a Deferred synchronously when direct allocation outside
Effect is required.
Example (Creating a Deferred unsafely)
import { Deferred } from "effect"
const deferred = Deferred.makeUnsafe<number>()
console.log(deferred)
makeUnsafe()
);
const const requestWake: Effect.Effect<
void,
never,
never
>
const requestWake: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
requestWake = import EffectEffect.const flatMap: <Deferred.Deferred<void, never>, never, never, boolean, never, never>(self: Effect.Effect<Deferred.Deferred<void, never>, never, never>, f: (a: Deferred.Deferred<void, never>) => Effect.Effect<boolean, never, never>) => Effect.Effect<boolean, never, never> (+1 overload)Chains effects to produce new Effect instances, useful for combining
operations that depend on previous results.
When to use
Use when you need to chain multiple effects, ensuring that each
step produces a new Effect while flattening any nested effects that may
occur.
Details
flatMap lets you sequence effects so that the result of one effect can be
used in the next step. It is similar to flatMap used with arrays but works
specifically with Effect instances, allowing you to avoid deeply nested
effect structures.
Since effects are immutable, flatMap always returns a new effect instead of
changing the original one.
Example (Choosing flatMap syntax variants)
import { Effect, pipe } from "effect"
const myEffect = Effect.succeed(1)
const transformation = (n: number) => Effect.succeed(n + 1)
const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation))
const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation)
const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation))
Example (Sequencing dependent effects)
import { Data, Effect, pipe } from "effect"
class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
// Function to apply a discount safely to a transaction amount
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, DiscountRateError> =>
discountRate === 0
? Effect.fail(new DiscountRateError())
: Effect.succeed(total - (total * discountRate) / 100)
// Simulated asynchronous task to fetch a transaction amount from database
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
// Chaining the fetch and discount application using `flatMap`
const finalAmount = pipe(
fetchTransactionAmount,
Effect.flatMap((amount) => applyDiscount(amount, 5))
)
Effect.runPromise(finalAmount).then(console.log)
// Output: 95
flatMap(import RefRef.const get: <Deferred.Deferred<void, never>>(self: Ref.Ref<Deferred.Deferred<void, never>>) => Effect.Effect<Deferred.Deferred<void, never>, never, never>Gets the current value of the Ref.
When to use
Use to read the current Ref value without changing it.
Example (Getting the current value)
import { Effect, Ref } from "effect"
const program = Effect.gen(function*() {
const ref = yield* Ref.make(42)
const value = yield* Ref.get(ref)
console.log(value) // 42
})
get(const wakeRef: Ref.Ref<
Deferred.Deferred<void, never>
>
const wakeRef: {
ref: MutableRef.MutableRef<A>;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
wakeRef), (d: Deferred.Deferred<void, never>(parameter) d: {
effect: Effect<A, E>;
resumes: Array<(effect: Effect<A, E>) => void> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
d) =>
import DeferredDeferred.const succeed: <void | undefined, never>(self: Deferred.Deferred<void | undefined, never>, value: void | undefined) => Effect.Effect<boolean> (+1 overload)Attempts to complete the Deferred with the specified value.
When to use
Use to complete a Deferred with a successful value.
Details
Fibers waiting on the Deferred receive the value only if this call
completes it. The returned effect succeeds with true when this call
completed the Deferred, or false if it was already completed.
Example (Completing a Deferred with a value)
import { Deferred, Effect } from "effect"
const program = Effect.gen(function*() {
const deferred = yield* Deferred.make<number>()
yield* Deferred.succeed(deferred, 42)
const value = yield* Deferred.await(deferred)
console.log(value) // 42
})
succeed(d: Deferred.Deferred<void, never>(parameter) d: {
effect: Effect<A, E>;
resumes: Array<(effect: Effect<A, E>) => void> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
d, var undefinedundefined)
).Pipeable.pipe<Effect.Effect<boolean, never, never>, Effect.Effect<void, never, never>>(this: Effect.Effect<boolean, never, never>, ab: (_: Effect.Effect<boolean, never, never>) => Effect.Effect<void, never, never>): Effect.Effect<void, never, never> (+21 overloads)pipe(import EffectEffect.const asVoid: <A, E, R>(
self: Effect.Effect<A, E, R>
) => Effect.Effect<void, E, R>
Maps the success value of an Effect to void, preserving failures.
Example (Discarding success values)
import { Effect } from "effect"
const program = Effect.asVoid(Effect.succeed(42))
Effect.runPromise(program).then(console.log)
// undefined (void)
asVoid);
const const awaitNextTick: Effect.Effect<
void,
never,
never
>
const awaitNextTick: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
awaitNextTick = import EffectEffect.const gen: <Effect.Effect<void, never, never>, void>(f: () => Generator<Effect.Effect<void, never, never>, void, never>) => Effect.Effect<void, never, never> (+1 overload)Provides a way to write effectful code using generator functions, simplifying
control flow and error handling.
When to use
Use when you want to write effectful code that looks and behaves like
synchronous code, while still handling asynchronous tasks, errors, and complex
control flow such as loops and conditions.
Generator functions work similarly to async/await but keep errors,
requirements, and interruption in the Effect type. You can yield* values
from effects and return the final result at the end.
Example (Sequencing effects with generators)
import { Data, Effect } from "effect"
class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, DiscountRateError> =>
discountRate === 0
? Effect.fail(new DiscountRateError())
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function*() {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})
gen(function* () {
const const d: Deferred.Deferred<void, never>const d: {
effect: Effect<A, E>;
resumes: Array<(effect: Effect<A, E>) => void> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
d = import DeferredDeferred.const makeUnsafe: <void, never>() => Deferred.Deferred<void, never>Creates an empty Deferred synchronously outside the Effect runtime.
When to use
Use to allocate a Deferred synchronously when direct allocation outside
Effect is required.
Example (Creating a Deferred unsafely)
import { Deferred } from "effect"
const deferred = Deferred.makeUnsafe<number>()
console.log(deferred)
makeUnsafe<void, never>();
yield* import RefRef.const set: <Deferred.Deferred<void, never>>(self: Ref.Ref<Deferred.Deferred<void, never>>, value: Deferred.Deferred<void, never>) => Effect.Effect<void> (+1 overload)set(const wakeRef: Ref.Ref<
Deferred.Deferred<void, never>
>
const wakeRef: {
ref: MutableRef.MutableRef<A>;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
wakeRef, const d: Deferred.Deferred<void, never>const d: {
effect: Effect<A, E>;
resumes: Array<(effect: Effect<A, E>) => void> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
d);
const const dur: Duration.Durationconst dur: {
value: DurationValue;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
dur = yield* const read: Effect.Effect<
Duration.Duration,
never,
never
>
const read: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
read;
yield* import EffectEffect.const race: <void, never, never, void, never, never>(self: Effect.Effect<void, never, never>, that: Effect.Effect<void, never, never>, options?: {
readonly onWinner?: (options: {
readonly fiber: Fiber<any, any>;
readonly index: number;
readonly parentFiber: Fiber<any, any>;
}) => void;
}) => Effect.Effect<void, never, never> (+1 overload)
Races two effects and returns the first successful result.
Details
If one effect succeeds, the other is interrupted and onWinner can observe the
winning fiber. If both fail, the race fails.
Example (Racing two effects)
import { Console, Duration, Effect } from "effect"
const fastFail = Effect.delay(Effect.fail("fast-fail"), Duration.millis(10))
const slowSuccess = Effect.delay(Effect.succeed("slow-success"), Duration.millis(50))
const program = Effect.gen(function*() {
const result = yield* Effect.race(fastFail, slowSuccess)
yield* Console.log(`winner: ${result}`)
})
Effect.runPromise(program)
// Output: winner: slow-success
race(import EffectEffect.const sleep: (
duration: Duration.Input
) => Effect.Effect<void>
Returns an effect that suspends the current fiber for the specified duration
without blocking a JavaScript thread.
Example (Pausing without blocking)
import { Console, Effect } from "effect"
const program = Effect.gen(function*() {
yield* Console.log("Start")
yield* Effect.sleep("2 seconds")
yield* Console.log("End")
})
Effect.runFork(program)
// Output: "Start" (immediately)
// Output: "End" (after 2 seconds)
sleep(const dur: Duration.Durationconst dur: {
value: DurationValue;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
dur), import DeferredDeferred.await<void, never>(self: Deferred.Deferred<void, never>): Effect.Effect<void, never, never>
export await
Retrieves the value of the Deferred, suspending the fiber running the
workflow until the result is available.
When to use
Use to wait for a Deferred to be completed and resume with its success,
failure, defect, or interruption.
Details
Awaiters observe the completion effect stored in the Deferred.
Example (Awaiting a Deferred value)
import { Deferred, Effect } from "effect"
const program = Effect.gen(function*() {
const deferred = yield* Deferred.make<number>()
yield* Deferred.succeed(deferred, 42)
const value = yield* Deferred.await(deferred)
console.log(value) // 42
})
await(const d: Deferred.Deferred<void, never>const d: {
effect: Effect<A, E>;
resumes: Array<(effect: Effect<A, E>) => void> | undefined;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
}
d)).Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<void, never, never>>(this: Effect.Effect<void, never, never>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<void, never, never>): Effect.Effect<void, never, never> (+21 overloads)pipe(
import EffectEffect.const asVoid: <A, E, R>(
self: Effect.Effect<A, E, R>
) => Effect.Effect<void, E, R>
Maps the success value of an Effect to void, preserving failures.
Example (Discarding success values)
import { Effect } from "effect"
const program = Effect.asVoid(Effect.succeed(42))
Effect.runPromise(program).then(console.log)
// undefined (void)
asVoid
);
});
// wake-on-swap: only when the field is swappable and the store is around
const const store: Option.Option<unknown>store = yield* import EffectEffect.const serviceOption: <unknown, unknown>(
key: Key<unknown, unknown>
) => Effect.Effect<
Option.Option<unknown>,
never,
never
>
Optionally accesses a service from the environment.
When to use
Use to read an optional dependency from the current context without making
that dependency part of the effect's required environment.
Details
This function attempts to access a service from the environment. If the
service is available, it returns Some(service). If the service is not
available, it returns None. Unlike service, this function does not
require the service to be present in the environment.
Example (Accessing an optional service)
import { Context, Effect, Option } from "effect"
// Define a service key
const Logger = Context.Service<{
log: (msg: string) => void
}>("Logger")
// Use serviceOption to optionally access the logger
const program = Effect.gen(function*() {
const maybeLogger = yield* Effect.serviceOption(Logger)
if (Option.isSome(maybeLogger)) {
maybeLogger.value.log("Service is available")
} else {
console.log("Service not available")
}
})
serviceOption(import DynamicConfigStoreDynamicConfigStore);
if ("changes" in field: anyfield && import OptionOption.const isSome: <unknown>(
self: Option.Option<unknown>
) => self is Option.Some<unknown>
Checks whether an Option contains a value (Some).
When to use
Use when you need to branch on a present Option before accessing .value.
Details
- Acts as a type guard, narrowing to
Some<A>
Example (Checking for Some)
import { Option } from "effect"
console.log(Option.isSome(Option.some(1)))
// Output: true
console.log(Option.isSome(Option.none()))
// Output: false
isSome(const store: Option.Option<unknown>store)) {
yield* import EffectEffect.const forkScoped: <Effect.Effect<void, unknown, never>>(effectOrOptions?: Effect.Effect<void, unknown, never> | undefined, options?: {
readonly startImmediately?: boolean | undefined;
readonly uninterruptible?: boolean | "inherit" | undefined;
} | undefined) => Effect.Effect<Fiber<void, unknown>, never, Scope.Scope>
Forks the fiber in a Scope, interrupting it when the scope is closed.
Example (Forking into the current scope)
import { Effect } from "effect"
const backgroundTask = Effect.gen(function*() {
yield* Effect.sleep("5 seconds")
yield* Effect.log("Background task completed")
return "result"
})
const program = Effect.scoped(
Effect.gen(function*() {
const fiber = yield* backgroundTask.pipe(Effect.forkScoped)
// or fork a fiber that starts immediately:
yield* backgroundTask.pipe(Effect.forkScoped({ startImmediately: true }))
yield* Effect.log("Task forked in scope")
yield* Effect.sleep("1 second")
// Fiber will be interrupted when scope closes
return "scope completed"
})
)
forkScoped(
import StreamStream.const runForEach: <unknown, unknown, unknown, void, never, never>(self: Stream.Stream<unknown, unknown, unknown>, f: (a: unknown) => Effect.Effect<void, never, never>) => Effect.Effect<void, unknown, unknown> (+1 overload)Runs the provided effectful callback for each element of the stream.
Example (Running an effect for each value)
import { Console, Effect, Stream } from "effect"
const stream = Stream.make(1, 2, 3)
const program = Effect.gen(function*() {
yield* Stream.runForEach(stream, (n) => Console.log(`Processing: ${n}`))
})
Effect.runPromise(program)
// Processing: 1
// Processing: 2
// Processing: 3
runForEach(field: anyfield.changes, () => const requestWake: Effect.Effect<
void,
never,
never
>
const requestWake: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
requestWake).Pipeable.pipe<Effect.Effect<void, unknown, unknown>, Effect.Effect<void, unknown, never>>(this: Effect.Effect<void, unknown, unknown>, ab: (_: Effect.Effect<void, unknown, unknown>) => Effect.Effect<void, unknown, never>): Effect.Effect<void, unknown, never> (+21 overloads)pipe(
import EffectEffect.const provideService: <unknown, unknown>(service: Key<unknown, unknown>, implementation: unknown) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, unknown>> (+2 overloads)Provides one concrete service implementation to an effect.
When to use
Use to satisfy one service requirement with an already-built implementation.
Details
The service requirement identified by the Context.Key is removed from the
effect requirements after the implementation is provided.
Example (Providing a service value)
import { Console, Context, Effect } from "effect"
// Define a service for configuration
const Config = Context.Service<{
apiUrl: string
timeout: number
}>("Config")
const fetchData = Effect.gen(function*() {
const config = yield* Effect.service(Config)
yield* Console.log(`Fetching from: ${config.apiUrl}`)
yield* Console.log(`Timeout: ${config.timeout}ms`)
return "data"
})
// Provide the service implementation
const program = Effect.provideService(fetchData, Config, {
apiUrl: "https://api.example.com",
timeout: 5000
})
Effect.runPromise(program).then(console.log)
// Output:
// Fetching from: https://api.example.com
// Timeout: 5000ms
// data
provideService(import DynamicConfigStoreDynamicConfigStore, const store: Option.Some<unknown>const store: {
_tag: "Some";
_op: "Some";
value: A;
valueOrUndefined: A;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
store.Some<unknown>.value: unknownvalue)
)
);
}
return {
awaitNextTick: Effect.Effect<void, never, never>(property) awaitNextTick: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
awaitNextTick,
requestWake: Effect.Effect<void, never, never>(property) requestWake: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
requestWake,
resetCadence: Effect.Effect<void, never, never>(property) resetCadence: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
resetCadence: const requestWake: Effect.Effect<
void,
never,
never
>
const requestWake: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
requestWake,
afterTick: Effect.Effect<void, never, never>(property) afterTick: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
afterTick: import EffectEffect.const void: Effect.Effect<void, never, never>
export void
(alias) const void: {
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
Returns an effect that succeeds with void.
void,
peekCadence: anypeekCadence: field: anyfield.pipe(
import EffectEffect.const map: <unknown, Option.Option<unknown>>(f: (a: unknown) => Option.Option<unknown>) => <E, R>(self: Effect.Effect<unknown, E, R>) => Effect.Effect<Option.Option<unknown>, E, R> (+1 overload)Transforms the value inside an effect by applying a function to it.
When to use
Use to transform an effect's success value with a function that returns a
plain value, producing a new effect without changing the original effect's
typed error or context requirements.
Details
map takes a function and applies it to the value contained within an
effect, creating a new effect with the transformed value.
It's important to note that effects are immutable, meaning that the original
effect is not modified. Instead, a new effect is returned with the updated
value.
Example (Choosing map syntax variants)
import { Effect, pipe } from "effect"
const myEffect = Effect.succeed(1)
const transformation = (n: number) => n + 1
const mappedWithPipe = pipe(myEffect, Effect.map(transformation))
const mappedWithDataFirst = Effect.map(myEffect, transformation)
const mappedWithMethod = myEffect.pipe(Effect.map(transformation))
Example (Adding a service charge)
import { Effect, pipe } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const finalAmount = pipe(
fetchTransactionAmount,
Effect.map(addServiceCharge)
)
Effect.runPromise(finalAmount).then(console.log)
// Output: 101
map(import OptionOption.const some: <A>(
value: A
) => Option.Option<A>
Wraps the given value into an Option to represent its presence.
When to use
Use to wrap a known present value as Option
- Returning a successful result from a partial function
Details
- Always returns
Some<A>
- Does not filter
null or undefined; use
fromNullishOr
for that
Example (Wrapping a value)
import { Option } from "effect"
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }
some),
import EffectEffect.catch<unknown, Option.None<Duration.Duration> | Option.Some<Duration.Duration>, never, never>(f: (e: unknown) => Effect.Effect<Option.None<Duration.Duration> | Option.Some<Duration.Duration>, never, never>): <A, R>(self: Effect.Effect<A, unknown, R>) => Effect.Effect<Option.None<Duration.Duration> | Option.Some<Duration.Duration> | A, never, R> (+1 overload)
export catch
catch(() =>
import EffectEffect.const succeed: <Option.None<Duration.Duration> | Option.Some<Duration.Duration>>(value: Option.None<Duration.Duration> | Option.Some<Duration.Duration>) => Effect.Effect<Option.None<Duration.Duration> | Option.Some<Duration.Duration>, never, never>Creates an Effect that always succeeds with a given value.
When to use
Use when an effect should complete successfully with a specific value without any errors
or external dependencies.
Example (Creating a successful effect)
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)
succeed(
const fallback:
| Duration.Duration
| undefined
fallback === var undefinedundefined ? import OptionOption.const none: <
never
>() => Option.Option<never>
Creates an Option representing the absence of a value.
When to use
Use to represent a missing or uninitialized value, such as returning "no
result" from a function.
Details
- Returns
Option<never>, which is a subtype of Option<A> for any A
- Always returns the same singleton instance
Example (Creating an empty Option)
import { Option } from "effect"
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }
none() : import OptionOption.const some: <Duration.Duration>(value: Duration.Duration) => Option.Option<Duration.Duration>Wraps the given value into an Option to represent its presence.
When to use
Use to wrap a known present value as Option
- Returning a successful result from a partial function
Details
- Always returns
Some<A>
- Does not filter
null or undefined; use
fromNullishOr
for that
Example (Wrapping a value)
import { Option } from "effect"
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }
some(const fallback: Duration.Durationconst fallback: {
value: DurationValue;
pipe: { <A>(this: A): A; <A, B = never>(this: A, ab: (_: A) => B): B; <A, B = never, C = never>(this: A, ab: (_: A) => B, bc: (_: B) => C): C; <A, B = never, C = never, D = never>(this: A, ab: (_: A) => B, bc: (_: B) => C, cd: (_: C) => D): D; <…;
toString: () => string;
toJSON: () => unknown;
}
fallback)
)
)
),
} satisfies import PollingServicePollingService;
})
)
);
};