Skip to main content Link Search Menu Expand Document (external link)

Effect overview

Added in v2.0.0


Table of contents


alternatives

orDie

Translates effect failure into death of the fiber, making all failures unchecked and not a part of the type of the effect.

Signature

export declare const orDie: <A, E, R>(self: Effect<A, E, R>) => Effect<A, never, R>

Added in v2.0.0

orDieWith

Keeps none of the errors, and terminates the fiber with them, using the specified function to convert the E into a Throwable.

Signature

export declare const orDieWith: {
  <E>(f: (error: E) => unknown): <A, R>(self: Effect<A, E, R>) => Effect<A, never, R>
  <A, E, R>(self: Effect<A, E, R>, f: (error: E) => unknown): Effect<A, never, R>
}

Added in v2.0.0

orElse

Executes this effect and returns its value, if it succeeds, but otherwise executes the specified effect.

Signature

export declare const orElse: {
  <A2, E2, R2>(that: LazyArg<Effect<A2, E2, R2>>): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2, R2 | R>
  <A, E, R, A2, E2, R2>(self: Effect<A, E, R>, that: LazyArg<Effect<A2, E2, R2>>): Effect<A | A2, E2, R | R2>
}

Added in v2.0.0

orElseFail

Executes this effect and returns its value, if it succeeds, but otherwise fails with the specified error.

Signature

export declare const orElseFail: {
  <E2>(evaluate: LazyArg<E2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E2, R>
  <A, E, R, E2>(self: Effect<A, E, R>, evaluate: LazyArg<E2>): Effect<A, E2, R>
}

Added in v2.0.0

orElseSucceed

Executes this effect and returns its value, if it succeeds, but otherwise succeeds with the specified value.

Signature

export declare const orElseSucceed: {
  <A2>(evaluate: LazyArg<A2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, never, R>
  <A, E, R, A2>(self: Effect<A, E, R>, evaluate: LazyArg<A2>): Effect<A | A2, never, R>
}

Added in v2.0.0

caching

cached

Returns an effect that computes a result lazily and caches it. Subsequent evaluations of this effect will return the cached result without re-executing the logic.

Signature

export declare const cached: <A, E, R>(self: Effect<A, E, R>) => Effect<Effect<A, E, R>, never, never>

Example

import { Effect, Console } from "effect"

let i = 1
const expensiveTask = Effect.promise<string>(() => {
  console.log("expensive task...")
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`result ${i++}`)
    }, 100)
  })
})

const program = Effect.gen(function* () {
  console.log("non-cached version:")
  yield* expensiveTask.pipe(Effect.andThen(Console.log))
  yield* expensiveTask.pipe(Effect.andThen(Console.log))
  console.log("cached version:")
  const cached = yield* Effect.cached(expensiveTask)
  yield* cached.pipe(Effect.andThen(Console.log))
  yield* cached.pipe(Effect.andThen(Console.log))
})

Effect.runFork(program)
// Output:
// non-cached version:
// expensive task...
// result 1
// expensive task...
// result 2
// cached version:
// expensive task...
// result 3
// result 3

Added in v2.0.0

cachedFunction

Returns a memoized version of a function with effects. Memoization ensures that results are stored and reused for the same inputs, reducing the need to recompute them.

Signature

export declare const cachedFunction: <A, B, E, R>(
  f: (a: A) => Effect<B, E, R>,
  eq?: Equivalence<A> | undefined
) => Effect<(a: A) => Effect<B, E, R>, never, never>

Example

import { Effect, Random } from "effect"

const program = Effect.gen(function* () {
  const randomNumber = (n: number) => Random.nextIntBetween(1, n)
  console.log("non-memoized version:")
  console.log(yield* randomNumber(10))
  console.log(yield* randomNumber(10))

  console.log("memoized version:")
  const memoized = yield* Effect.cachedFunction(randomNumber)
  console.log(yield* memoized(10))
  console.log(yield* memoized(10))
})

Effect.runFork(program)
// Example Output:
// non-memoized version:
// 2
// 8
// memoized version:
// 5
// 5

Added in v2.0.0

cachedInvalidateWithTTL

Similar to {@link cachedWithTTL}, this function caches an effect’s result for a specified duration. It also includes an additional effect for manually invalidating the cached value before it naturally expires.

Signature

export declare const cachedInvalidateWithTTL: {
  (
    timeToLive: Duration.DurationInput
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<[Effect<A, E, never>, Effect<void, never, never>], never, R>
  <A, E, R>(
    self: Effect<A, E, R>,
    timeToLive: Duration.DurationInput
  ): Effect<[Effect<A, E, never>, Effect<void, never, never>], never, R>
}

Example

import { Effect, Console } from "effect"

let i = 1
const expensiveTask = Effect.promise<string>(() => {
  console.log("expensive task...")
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`result ${i++}`)
    }, 100)
  })
})

const program = Effect.gen(function* () {
  const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL(expensiveTask, "1 hour")
  yield* cached.pipe(Effect.andThen(Console.log))
  yield* cached.pipe(Effect.andThen(Console.log))
  yield* invalidate
  yield* cached.pipe(Effect.andThen(Console.log))
})

Effect.runFork(program)
// Output:
// expensive task...
// result 1
// result 1
// expensive task...
// result 2

Added in v2.0.0

cachedWithTTL

Returns an effect that caches its result for a specified duration, known as the timeToLive. When the cache expires after the duration, the effect will be recomputed upon next evaluation.

Signature

export declare const cachedWithTTL: {
  (timeToLive: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<Effect<A, E, never>, never, R>
  <A, E, R>(self: Effect<A, E, R>, timeToLive: Duration.DurationInput): Effect<Effect<A, E, never>, never, R>
}

Example

import { Effect, Console } from "effect"

let i = 1
const expensiveTask = Effect.promise<string>(() => {
  console.log("expensive task...")
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`result ${i++}`)
    }, 100)
  })
})

const program = Effect.gen(function* () {
  const cached = yield* Effect.cachedWithTTL(expensiveTask, "150 millis")
  yield* cached.pipe(Effect.andThen(Console.log))
  yield* cached.pipe(Effect.andThen(Console.log))
  yield* Effect.sleep("100 millis")
  yield* cached.pipe(Effect.andThen(Console.log))
})

Effect.runFork(program)
// Output:
// expensive task...
// result 1
// result 1
// expensive task...
// result 2

Added in v2.0.0

once

Returns an effect that executes only once, regardless of how many times it’s called.

Signature

export declare const once: <A, E, R>(self: Effect<A, E, R>) => Effect<Effect<void, E, R>, never, never>

Example

import { Effect, Console } from "effect"

const program = Effect.gen(function* () {
  const task1 = Console.log("task1")
  yield* Effect.repeatN(task1, 2)
  const task2 = yield* Effect.once(Console.log("task2"))
  yield* Effect.repeatN(task2, 2)
})

Effect.runFork(program)
// Output:
// task1
// task1
// task1
// task2

Added in v2.0.0

clock

clock

Retreives the Clock service from the context

Signature

export declare const clock: Effect<Clock.Clock, never, never>

Added in v2.0.0

clockWith

Retreives the Clock service from the context and provides it to the specified effectful function.

Signature

export declare const clockWith: <A, E, R>(f: (clock: Clock.Clock) => Effect<A, E, R>) => Effect<A, E, R>

Added in v2.0.0

withClock

Executes the specified workflow with the specified implementation of the clock service.

Signature

export declare const withClock: {
  <X extends Clock.Clock>(value: X): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>
  <X extends Clock.Clock, A, E, R>(effect: Effect<A, E, R>, value: X): Effect<A, E, R>
}

Added in v2.0.0

collecting & elements

all

Runs all the provided effects in sequence respecting the structure provided in input.

Supports multiple arguments, a single argument tuple / array or record / struct.

Signature

export declare const all: <
  const Arg extends Iterable<Effect<any, any, any>> | Record<string, Effect<any, any, any>>,
  O extends {
    readonly concurrency?: Concurrency | undefined
    readonly batching?: boolean | "inherit" | undefined
    readonly discard?: boolean | undefined
    readonly mode?: "default" | "validate" | "either" | undefined
  }
>(
  arg: Arg,
  options?: O | undefined
) => All.Return<Arg, O>

Added in v2.0.0

allSuccesses

Evaluate and run each effect in the structure and collect the results, discarding results from failed effects.

Signature

export declare const allSuccesses: <X extends Effect<any, any, any>>(
  elements: Iterable<X>,
  options?:
    | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
    | undefined
) => Effect<Effect.Success<X>[], never, Effect.Context<X>>

Added in v2.0.0

allWith

Data-last variant of Effect.all.

Runs all the provided effects in sequence respecting the structure provided in input.

Supports multiple arguments, a single argument tuple / array or record / struct.

Signature

export declare const allWith: <
  O extends {
    readonly concurrency?: Concurrency | undefined
    readonly batching?: boolean | "inherit" | undefined
    readonly discard?: boolean | undefined
    readonly mode?: "default" | "validate" | "either" | undefined
  }
>(
  options?: O | undefined
) => <const Arg extends Iterable<Effect<any, any, any>> | Record<string, Effect<any, any, any>>>(
  arg: Arg
) => All.Return<Arg, O>

Added in v2.0.0

dropUntil

Drops all elements until the effectful predicate returns true.

Signature

export declare const dropUntil: {
  <A, E, R>(
    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>
  ): (elements: Iterable<A>) => Effect<A[], E, R>
  <A, E, R>(elements: Iterable<A>, predicate: (a: A, i: number) => Effect<boolean, E, R>): Effect<A[], E, R>
}

Added in v2.0.0

dropWhile

Drops all elements so long as the predicate returns true.

Signature

export declare const dropWhile: {
  <A, E, R>(
    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>
  ): (elements: Iterable<A>) => Effect<A[], E, R>
  <A, E, R>(elements: Iterable<A>, predicate: (a: A, i: number) => Effect<boolean, E, R>): Effect<A[], E, R>
}

Added in v2.0.0

every

Determines whether all elements of the Collection<A> satisfies the effectual predicate f.

Signature

export declare const every: {
  <A, E, R>(f: (a: A, i: number) => Effect<boolean, E, R>): (elements: Iterable<A>) => Effect<boolean, E, R>
  <A, E, R>(elements: Iterable<A>, f: (a: A, i: number) => Effect<boolean, E, R>): Effect<boolean, E, R>
}

Added in v2.0.0

exists

Determines whether any element of the Iterable<A> satisfies the effectual predicate f.

Signature

export declare const exists: {
  <A, E, R>(
    f: (a: A, i: number) => Effect<boolean, E, R>,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): (elements: Iterable<A>) => Effect<boolean, E, R>
  <A, E, R>(
    elements: Iterable<A>,
    f: (a: A, i: number) => Effect<boolean, E, R>,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): Effect<boolean, E, R>
}

Added in v2.0.0

filter

Filters the collection using the specified effectful predicate.

Signature

export declare const filter: {
  <A, E, R>(
    f: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>,
    options?:
      | {
          readonly concurrency?: Concurrency | undefined
          readonly batching?: boolean | "inherit" | undefined
          readonly negate?: boolean | undefined
        }
      | undefined
  ): (elements: Iterable<A>) => Effect<A[], E, R>
  <A, E, R>(
    elements: Iterable<A>,
    f: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>,
    options?:
      | {
          readonly concurrency?: Concurrency | undefined
          readonly batching?: boolean | "inherit" | undefined
          readonly negate?: boolean | undefined
        }
      | undefined
  ): Effect<A[], E, R>
}

Added in v2.0.0

filterMap

Performs a filter and map in a single step.

Signature

export declare const filterMap: {
  <Eff extends Effect<any, any, any>, B>(
    pf: (a: Effect.Success<Eff>) => Option.Option<B>
  ): (elements: Iterable<Eff>) => Effect<B[], Effect.Error<Eff>, Effect.Context<Eff>>
  <Eff extends Effect<any, any, any>, B>(
    elements: Iterable<Eff>,
    pf: (a: Effect.Success<Eff>) => Option.Option<B>
  ): Effect<B[], Effect.Error<Eff>, Effect.Context<Eff>>
}

Added in v2.0.0

findFirst

Returns the first element that satisfies the effectful predicate.

Signature

export declare const findFirst: {
  <A, E, R>(
    f: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>
  ): (elements: Iterable<A>) => Effect<Option.Option<A>, E, R>
  <A, E, R>(
    elements: Iterable<A>,
    f: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>
  ): Effect<Option.Option<A>, E, R>
}

Added in v2.0.0

firstSuccessOf

This function takes an iterable of Effect values and returns a new Effect value that represents the first Effect value in the iterable that succeeds. If all of the Effect values in the iterable fail, then the resulting Effect value will fail as well.

This function is sequential, meaning that the Effect values in the iterable will be executed in sequence, and the first one that succeeds will determine the outcome of the resulting Effect value.

Signature

export declare const firstSuccessOf: <Eff extends Effect<any, any, any>>(
  effects: Iterable<Eff>
) => Effect<Effect.Success<Eff>, Effect.Error<Eff>, Effect.Context<Eff>>

Added in v2.0.0

forEach

Signature

export declare const forEach: {
  <B, E, R, S extends Iterable<any>>(
    f: (a: RA.ReadonlyArray.Infer<S>, i: number) => Effect<B, E, R>,
    options?:
      | {
          readonly concurrency?: Concurrency | undefined
          readonly batching?: boolean | "inherit" | undefined
          readonly discard?: false | undefined
        }
      | undefined
  ): (self: S) => Effect<RA.ReadonlyArray.With<S, B>, E, R>
  <A, B, E, R>(
    f: (a: A, i: number) => Effect<B, E, R>,
    options: {
      readonly concurrency?: Concurrency | undefined
      readonly batching?: boolean | "inherit" | undefined
      readonly discard: true
    }
  ): (self: Iterable<A>) => Effect<void, E, R>
  <B, E, R, S extends Iterable<any>>(
    self: S,
    f: (a: RA.ReadonlyArray.Infer<S>, i: number) => Effect<B, E, R>,
    options?:
      | {
          readonly concurrency?: Concurrency | undefined
          readonly batching?: boolean | "inherit" | undefined
          readonly discard?: false | undefined
        }
      | undefined
  ): Effect<RA.ReadonlyArray.With<S, B>, E, R>
  <A, B, E, R>(
    self: Iterable<A>,
    f: (a: A, i: number) => Effect<B, E, R>,
    options: {
      readonly concurrency?: Concurrency | undefined
      readonly batching?: boolean | "inherit" | undefined
      readonly discard: true
    }
  ): Effect<void, E, R>
}

Added in v2.0.0

Returns a successful effect with the head of the collection if the collection is non-empty, or fails with the error None if the collection is empty.

Signature

export declare const head: <A, E, R>(self: Effect<Iterable<A>, E, R>) => Effect<A, Cause.NoSuchElementException | E, R>

Added in v2.0.0

mergeAll

Merges an Iterable<Effect<A, E, R>> to a single effect, working sequentially.

Signature

export declare const mergeAll: {
  <Z, Eff extends Effect<any, any, any>>(
    zero: Z,
    f: (z: Z, a: Effect.Success<Eff>, i: number) => Z,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): (elements: Iterable<Eff>) => Effect<Z, Effect.Error<Eff>, Effect.Context<Eff>>
  <Eff extends Effect<any, any, any>, Z>(
    elements: Iterable<Eff>,
    zero: Z,
    f: (z: Z, a: Effect.Success<Eff>, i: number) => Z,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): Effect<Z, Effect.Error<Eff>, Effect.Context<Eff>>
}

Added in v2.0.0

partition

Feeds elements of type A to a function f that returns an effect. Collects all successes and failures in a tupled fashion.

Signature

export declare const partition: {
  <A, B, E, R>(
    f: (a: A, i: number) => Effect<B, E, R>,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): (elements: Iterable<A>) => Effect<[excluded: E[], satisfying: B[]], never, R>
  <A, B, E, R>(
    elements: Iterable<A>,
    f: (a: A, i: number) => Effect<B, E, R>,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): Effect<[excluded: E[], satisfying: B[]], never, R>
}

Added in v2.0.0

reduce

Folds an Iterable<A> using an effectual function f, working sequentially from left to right.

Signature

export declare const reduce: {
  <Z, A, E, R>(zero: Z, f: (z: Z, a: A, i: number) => Effect<Z, E, R>): (elements: Iterable<A>) => Effect<Z, E, R>
  <A, Z, E, R>(elements: Iterable<A>, zero: Z, f: (z: Z, a: A, i: number) => Effect<Z, E, R>): Effect<Z, E, R>
}

Added in v2.0.0

reduceEffect

Reduces an Iterable<Effect<A, E, R>> to a single effect.

Signature

export declare const reduceEffect: {
  <Z, E, R, Eff extends Effect<any, any, any>>(
    zero: Effect<Z, E, R>,
    f: (acc: NoInfer<Z>, a: Effect.Success<Eff>, i: number) => Z,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): (elements: Iterable<Eff>) => Effect<Z, E | Effect.Error<Eff>, R | Effect.Context<Eff>>
  <Eff extends Effect<any, any, any>, Z, E, R>(
    elements: Iterable<Eff>,
    zero: Effect<Z, E, R>,
    f: (acc: NoInfer<Z>, a: Effect.Success<Eff>, i: number) => Z,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): Effect<Z, E | Effect.Error<Eff>, R | Effect.Context<Eff>>
}

Added in v2.0.0

reduceRight

Folds an Iterable<A> using an effectual function f, working sequentially from left to right.

Signature

export declare const reduceRight: {
  <A, Z, R, E>(zero: Z, f: (a: A, z: Z, i: number) => Effect<Z, E, R>): (elements: Iterable<A>) => Effect<Z, E, R>
  <A, Z, R, E>(elements: Iterable<A>, zero: Z, f: (a: A, z: Z, i: number) => Effect<Z, E, R>): Effect<Z, E, R>
}

Added in v2.0.0

reduceWhile

Folds over the elements in this chunk from the left, stopping the fold early when the predicate is not satisfied.

Signature

export declare const reduceWhile: {
  <Z, A, E, R>(
    zero: Z,
    options: { readonly while: Predicate<Z>; readonly body: (s: Z, a: A, i: number) => Effect<Z, E, R> }
  ): (elements: Iterable<A>) => Effect<Z, E, R>
  <A, Z, E, R>(
    elements: Iterable<A>,
    zero: Z,
    options: { readonly while: Predicate<Z>; readonly body: (s: Z, a: A, i: number) => Effect<Z, E, R> }
  ): Effect<Z, E, R>
}

Added in v2.0.0

replicate

Replicates the given effect n times.

Signature

export declare const replicate: {
  (n: number): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>[]
  <A, E, R>(self: Effect<A, E, R>, n: number): Effect<A, E, R>[]
}

Added in v2.0.0

replicateEffect

Performs this effect the specified number of times and collects the results.

Signature

export declare const replicateEffect: {
  (
    n: number,
    options?: {
      readonly concurrency?: Concurrency | undefined
      readonly batching?: boolean | "inherit" | undefined
      readonly discard?: false | undefined
    }
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A[], E, R>
  (
    n: number,
    options: {
      readonly concurrency?: Concurrency | undefined
      readonly batching?: boolean | "inherit" | undefined
      readonly discard: true
    }
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<void, E, R>
  <A, E, R>(
    self: Effect<A, E, R>,
    n: number,
    options?: {
      readonly concurrency?: Concurrency | undefined
      readonly batching?: boolean | "inherit" | undefined
      readonly discard?: false | undefined
    }
  ): Effect<A[], E, R>
  <A, E, R>(
    self: Effect<A, E, R>,
    n: number,
    options: {
      readonly concurrency?: Concurrency | undefined
      readonly batching?: boolean | "inherit" | undefined
      readonly discard: true
    }
  ): Effect<void, E, R>
}

Added in v2.0.0

takeUntil

Takes elements until the effectual predicate returns true.

Signature

export declare const takeUntil: {
  <A, R, E>(
    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>
  ): (elements: Iterable<A>) => Effect<A[], E, R>
  <A, E, R>(elements: Iterable<A>, predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>): Effect<A[], E, R>
}

Added in v2.0.0

takeWhile

Takes all elements so long as the effectual predicate returns true.

Signature

export declare const takeWhile: {
  <A, E, R>(
    predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>
  ): (elements: Iterable<A>) => Effect<A[], E, R>
  <A, E, R>(elements: Iterable<A>, predicate: (a: NoInfer<A>, i: number) => Effect<boolean, E, R>): Effect<A[], E, R>
}

Added in v2.0.0

validateAll

Feeds elements of type A to f and accumulates all errors in error channel or successes in success channel.

This combinator is lossy meaning that if there are errors all successes will be lost. To retain all information please use partition.

Signature

export declare const validateAll: {
  <A, B, E, R>(
    f: (a: A, i: number) => Effect<B, E, R>,
    options?:
      | {
          readonly concurrency?: Concurrency | undefined
          readonly batching?: boolean | "inherit" | undefined
          readonly discard?: false | undefined
        }
      | undefined
  ): (elements: Iterable<A>) => Effect<B[], E[], R>
  <A, B, E, R>(
    f: (a: A, i: number) => Effect<B, E, R>,
    options: {
      readonly concurrency?: Concurrency | undefined
      readonly batching?: boolean | "inherit" | undefined
      readonly discard: true
    }
  ): (elements: Iterable<A>) => Effect<void, E[], R>
  <A, B, E, R>(
    elements: Iterable<A>,
    f: (a: A, i: number) => Effect<B, E, R>,
    options?:
      | {
          readonly concurrency?: Concurrency | undefined
          readonly batching?: boolean | "inherit" | undefined
          readonly discard?: false | undefined
        }
      | undefined
  ): Effect<B[], E[], R>
  <A, B, E, R>(
    elements: Iterable<A>,
    f: (a: A, i: number) => Effect<B, E, R>,
    options: {
      readonly concurrency?: Concurrency | undefined
      readonly batching?: boolean | "inherit" | undefined
      readonly discard: true
    }
  ): Effect<void, E[], R>
}

Added in v2.0.0

validateFirst

Feeds elements of type A to f until it succeeds. Returns first success or the accumulation of all errors.

If elements is empty then Effect.fail([]) is returned.

Signature

export declare const validateFirst: {
  <A, B, E, R>(
    f: (a: A, i: number) => Effect<B, E, R>,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): (elements: Iterable<A>) => Effect<B, E[], R>
  <A, B, E, R>(
    elements: Iterable<A>,
    f: (a: A, i: number) => Effect<B, E, R>,
    options?:
      | { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined }
      | undefined
  ): Effect<B, E[], R>
}

Example

import { Effect, Exit } from "effect"

const f = (n: number) => (n > 0 ? Effect.succeed(n) : Effect.fail(`${n} is negative`))

assert.deepStrictEqual(Effect.runSyncExit(Effect.validateFirst([], f)), Exit.fail([]))
assert.deepStrictEqual(Effect.runSyncExit(Effect.validateFirst([1, 2], f)), Exit.succeed(1))
assert.deepStrictEqual(Effect.runSyncExit(Effect.validateFirst([1, -1], f)), Exit.succeed(1))
assert.deepStrictEqual(Effect.runSyncExit(Effect.validateFirst([-1, 2], f)), Exit.succeed(2))
assert.deepStrictEqual(
  Effect.runSyncExit(Effect.validateFirst([-1, -2], f)),
  Exit.fail(["-1 is negative", "-2 is negative"])
)

Added in v2.0.0

combining

ap

Signature

export declare const ap: {
  <A, E2, R2>(that: Effect<A, E2, R2>): <B, R, E>(self: Effect<(a: A) => B, E, R>) => Effect<B, E2 | E, R2 | R>
  <A, B, E, R, E2, R2>(self: Effect<(a: A) => B, E, R>, that: Effect<A, E2, R2>): Effect<B, E | E2, R | R2>
}

Added in v2.0.0

config

configProviderWith

Retrieves the default config provider, and passes it to the specified function, which may return an effect that uses the provider to perform some work or compute some value.

Signature

export declare const configProviderWith: <A, E, R>(
  f: (configProvider: ConfigProvider) => Effect<A, E, R>
) => Effect<A, E, R>

Added in v2.0.0

withConfigProvider

Executes the specified workflow with the specified configuration provider.

Signature

export declare const withConfigProvider: {
  (value: ConfigProvider): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(effect: Effect<A, E, R>, value: ConfigProvider): Effect<A, E, R>
}

Added in v2.0.0

withConfigProviderScoped

Sets the configuration provider to the specified value and restores it to its original value when the scope is closed.

Signature

export declare const withConfigProviderScoped: (value: ConfigProvider) => Effect<void, never, Scope.Scope>

Added in v2.0.0

console

console

Retreives the Console service from the context

Signature

export declare const console: Effect<Console, never, never>

Added in v2.0.0

consoleWith

Retreives the Console service from the context and provides it to the specified effectful function.

Signature

export declare const consoleWith: <A, E, R>(f: (console: Console) => Effect<A, E, R>) => Effect<A, E, R>

Added in v2.0.0

withConsole

Executes the specified workflow with the specified implementation of the console service.

Signature

export declare const withConsole: {
  <C extends Console>(console: C): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R, C extends Console>(effect: Effect<A, E, R>, console: C): Effect<A, E, R>
}

Added in v2.0.0

constructors

Tag

Signature

export declare const Tag: <const Id extends string>(
  id: Id
) => <Self, Type extends Tag.AllowedType>() => Context.TagClass<Self, Id, Type> &
  (Type extends Record<PropertyKey, any>
    ? {
        [k in keyof Type as Type[k] extends (...args_0: infer Args) => infer Ret
          ? ((...args: Readonly<Args>) => Ret) extends Type[k]
            ? k
            : never
          : k]: Type[k] extends (...args_0: infer Args) => Effect<infer A, infer E, infer R>
          ? (...args: Readonly<Args>) => Effect<A, E, Self | R>
          : Type[k] extends (...args_0: infer Args) => infer A
            ? (...args: Readonly<Args>) => Effect<A, never, Self>
            : Type[k] extends Effect<infer A, infer E, infer R>
              ? Effect<A, E, Self | R>
              : Effect<Type[k], never, Self>
      }
    : {}) & {
    use: <X>(
      body: (_: Type) => X
    ) => X extends Effect<infer A, infer E, infer R> ? Effect<A, E, Self | R> : Effect<X, never, Self>
  }

Added in v2.0.0

async

Imports an asynchronous side-effect into a pure Effect value. The callback function Effect<A, E, R> => void MUST be called at most once.

The registration function can optionally return an Effect, which will be executed if the Fiber executing this Effect is interrupted.

The registration function can also receive an AbortSignal if required for interruption.

The FiberId of the fiber that may complete the async callback may also be specified. This is called the “blocking fiber” because it suspends the fiber executing the async Effect (i.e. semantically blocks the fiber from making progress). Specifying this fiber id in cases where it is known will improve diagnostics, but not affect the behavior of the returned effect.

Signature

export declare const async: <A, E = never, R = never>(
  register: (callback: (_: Effect<A, E, R>) => void, signal: AbortSignal) => void | Effect<void, never, R>,
  blockingOn?: FiberId.FiberId
) => Effect<A, E, R>

Added in v2.0.0

asyncEffect

Converts an asynchronous, callback-style API into an Effect, which will be executed asynchronously.

With this variant, the registration function may return a an Effect.

Signature

export declare const asyncEffect: <A, E, R, R3, E2, R2>(
  register: (callback: (_: Effect<A, E, R>) => void) => Effect<void | Effect<void, never, R3>, E2, R2>
) => Effect<A, E | E2, R | R3 | R2>

Added in v2.0.0

custom

Low level constructor that enables for custom stack tracing cutpoints.

It is meant to be called with a bag of instructions that become available in the “this” of the effect.

Signature

export declare const custom: {
  <X, A, E, R>(i0: X, body: (this: { effect_instruction_i0: X }) => Effect<A, E, R>): Effect<A, E, R>
  <X, Y, A, E, R>(
    i0: X,
    i1: Y,
    body: (this: { effect_instruction_i0: X; effect_instruction_i1: Y }) => Effect<A, E, R>
  ): Effect<A, E, R>
  <X, Y, Z, A, E, R>(
    i0: X,
    i1: Y,
    i2: Z,
    body: (this: { effect_instruction_i0: X; effect_instruction_i1: Y; effect_instruction_i2: Z }) => Effect<A, E, R>
  ): Effect<A, E, R>
}

Example

import { Effect } from "effect"

const throwingFunction = () => {
  throw new Error()
}
const blowUp = Effect.custom(throwingFunction, function () {
  return Effect.succeed(this.effect_instruction_i0())
})

Added in v2.0.0

die

Signature

export declare const die: (defect: unknown) => Effect<never>

Added in v2.0.0

dieMessage

Returns an effect that dies with a RuntimeException having the specified text message. This method can be used for terminating a fiber because a defect has been detected in the code.

Signature

export declare const dieMessage: (message: string) => Effect<never>

Added in v2.0.0

dieSync

Signature

export declare const dieSync: (evaluate: LazyArg<unknown>) => Effect<never>

Added in v2.0.0

fail

Signature

export declare const fail: <E>(error: E) => Effect<never, E, never>

Added in v2.0.0

failCause

Signature

export declare const failCause: <E>(cause: Cause.Cause<E>) => Effect<never, E, never>

Added in v2.0.0

failCauseSync

Signature

export declare const failCauseSync: <E>(evaluate: LazyArg<Cause.Cause<E>>) => Effect<never, E, never>

Added in v2.0.0

failSync

Signature

export declare const failSync: <E>(evaluate: LazyArg<E>) => Effect<never, E, never>

Added in v2.0.0

gen

Signature

export declare const gen: {
  <Eff extends YieldWrap<Effect<any, any, any>>, AEff>(
    f: (resume: Adapter) => Generator<Eff, AEff, never>
  ): Effect<
    AEff,
    [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,
    [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never
  >
  <Self, Eff extends YieldWrap<Effect<any, any, any>>, AEff>(
    self: Self,
    f: (this: Self, resume: Adapter) => Generator<Eff, AEff, never>
  ): Effect<
    AEff,
    [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer E, infer _R>>] ? E : never,
    [Eff] extends [never] ? never : [Eff] extends [YieldWrap<Effect<infer _A, infer _E, infer R>>] ? R : never
  >
}

Added in v2.0.0

never

Returns an effect that will never produce anything. The moral equivalent of while(true) {}, only without the wasted CPU cycles.

Signature

export declare const never: Effect<never, never, never>

Added in v2.0.0

none

Requires the option produced by this value to be None.

Signature

export declare const none: <A, E, R>(
  self: Effect<Option.Option<A>, E, R>
) => Effect<void, Cause.NoSuchElementException | E, R>

Added in v2.0.0

promise

Like tryPromise but produces a defect in case of errors.

An optional AbortSignal can be provided to allow for interruption of the wrapped Promise api.

Signature

export declare const promise: <A>(evaluate: (signal: AbortSignal) => PromiseLike<A>) => Effect<A, never, never>

Added in v2.0.0

succeed

Signature

export declare const succeed: <A>(value: A) => Effect<A, never, never>

Added in v2.0.0

succeedNone

Returns an effect which succeeds with None.

Signature

export declare const succeedNone: Effect<Option.Option<never>, never, never>

Added in v2.0.0

succeedSome

Returns an effect which succeeds with the value wrapped in a Some.

Signature

export declare const succeedSome: <A>(value: A) => Effect<Option.Option<A>, never, never>

Added in v2.0.0

suspend

Signature

export declare const suspend: <A, E, R>(effect: LazyArg<Effect<A, E, R>>) => Effect<A, E, R>

Added in v2.0.0

sync

Signature

export declare const sync: <A>(evaluate: LazyArg<A>) => Effect<A, never, never>

Added in v2.0.0

void

Signature

export declare const void: Effect<void, never, never>

Added in v2.0.0

withClockScoped

Sets the implementation of the clock service to the specified value and restores it to its original value when the scope is closed.

Signature

export declare const withClockScoped: <A extends Clock.Clock>(value: A) => Effect<void, never, Scope.Scope>

Added in v2.0.0

withConsoleScoped

Sets the implementation of the console service to the specified value and restores it to its original value when the scope is closed.

Signature

export declare const withConsoleScoped: <A extends Console>(console: A) => Effect<void, never, Scope.Scope>

Added in v2.0.0

withFiberRuntime

Signature

export declare const withFiberRuntime: <A, E = never, R = never>(
  withRuntime: (fiber: Fiber.RuntimeFiber<A, E>, status: FiberStatus.Running) => Effect<A, E, R>
) => Effect<A, E, R>

Added in v2.0.0

withRandomScoped

Sets the implementation of the random service to the specified value and restores it to its original value when the scope is closed.

Signature

export declare const withRandomScoped: <A extends Random.Random>(value: A) => Effect<void, never, Scope.Scope>

Added in v2.0.0

yieldNow

Signature

export declare const yieldNow: (options?: { readonly priority?: number | undefined }) => Effect<void>

Added in v2.0.0

context

context

Signature

export declare const context: <R>() => Effect<Context.Context<R>, never, R>

Added in v2.0.0

contextWith

Accesses the context of the effect.

Signature

export declare const contextWith: <R, A>(f: (context: Context.Context<R>) => A) => Effect<A, never, R>

Added in v2.0.0

contextWithEffect

Effectually accesses the context of the effect.

Signature

export declare const contextWithEffect: <R0, A, E, R>(
  f: (context: Context.Context<R0>) => Effect<A, E, R>
) => Effect<A, E, R0 | R>

Added in v2.0.0

mapInputContext

Provides some of the context required to run this effect, leaving the remainder R0.

Signature

export declare const mapInputContext: {
  <R0, R>(f: (context: Context.Context<R0>) => Context.Context<R>): <A, E>(self: Effect<A, E, R>) => Effect<A, E, R0>
  <A, E, R, R0>(self: Effect<A, E, R>, f: (context: Context.Context<R0>) => Context.Context<R>): Effect<A, E, R0>
}

Added in v2.0.0

provide

Splits the context into two parts, providing one part using the specified layer/context/runtime and leaving the remainder R0

Signature

export declare const provide: {
  <ROut, E2, RIn>(
    layer: Layer.Layer<ROut, E2, RIn>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E2 | E, RIn | Exclude<R, ROut>>
  <R2>(context: Context.Context<R2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, Exclude<R, R2>>
  <R2>(runtime: Runtime.Runtime<R2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, Exclude<R, R2>>
  <A, E, R, ROut, E2, RIn>(
    self: Effect<A, E, R>,
    layer: Layer.Layer<ROut, E2, RIn>
  ): Effect<A, E | E2, RIn | Exclude<R, ROut>>
  <A, E, R, R2>(self: Effect<A, E, R>, context: Context.Context<R2>): Effect<A, E, Exclude<R, R2>>
  <A, E, R, R2>(self: Effect<A, E, R>, runtime: Runtime.Runtime<R2>): Effect<A, E, Exclude<R, R2>>
}

Added in v2.0.0

provideService

Provides the effect with the single service it requires. If the effect requires more than one service use provide instead.

Signature

export declare const provideService: {
  <T extends Context.Tag<any, any>>(
    tag: T,
    service: Context.Tag.Service<T>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, Exclude<R, Context.Tag.Identifier<T>>>
  <A, E, R, T extends Context.Tag<any, any>>(
    self: Effect<A, E, R>,
    tag: T,
    service: Context.Tag.Service<T>
  ): Effect<A, E, Exclude<R, Context.Tag.Identifier<T>>>
}

Added in v2.0.0

provideServiceEffect

Provides the effect with the single service it requires. If the effect requires more than one service use provide instead.

Signature

export declare const provideServiceEffect: {
  <T extends Context.Tag<any, any>, E1, R1>(
    tag: T,
    effect: Effect<Context.Tag.Service<T>, E1, R1>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E1 | E, R1 | Exclude<R, Context.Tag.Identifier<T>>>
  <A, E, R, T extends Context.Tag<any, any>, E1, R1>(
    self: Effect<A, E, R>,
    tag: T,
    effect: Effect<Context.Tag.Service<T>, E1, R1>
  ): Effect<A, E | E1, R1 | Exclude<R, Context.Tag.Identifier<T>>>
}

Added in v2.0.0

serviceConstants

Signature

export declare const serviceConstants: <S, SE, SR>(
  getService: Effect<S, SE, SR>
) => {
  [k in { [k in keyof S]: k }[keyof S]]: S[k] extends Effect<infer A, infer E, infer R>
    ? Effect<A, SE | E, SR | R>
    : Effect<S[k], SE, SR>
}

Added in v2.0.0

serviceFunction

Signature

export declare const serviceFunction: <T extends Effect<any, any, any>, Args extends any[], A>(
  getService: T,
  f: (_: Effect.Success<T>) => (...args: Args) => A
) => (...args: Args) => Effect<A, Effect.Error<T>, Effect.Context<T>>

Added in v2.0.0

serviceFunctionEffect

Signature

export declare const serviceFunctionEffect: <T extends Effect<any, any, any>, Args extends any[], A, E, R>(
  getService: T,
  f: (_: Effect.Success<T>) => (...args: Args) => Effect<A, E, R>
) => (...args: Args) => Effect<A, E | Effect.Error<T>, R | Effect.Context<T>>

Added in v2.0.0

serviceFunctions

Signature

export declare const serviceFunctions: <S, SE, SR>(
  getService: Effect<S, SE, SR>
) => {
  [k in keyof S as S[k] extends (...args: Array<any>) => Effect<any, any, any> ? k : never]: S[k] extends (
    ...args: infer Args
  ) => Effect<infer A, infer E, infer R>
    ? (...args: Args) => Effect<A, SE | E, SR | R>
    : never
}

Added in v2.0.0

serviceMembers

Signature

export declare const serviceMembers: <S, SE, SR>(
  getService: Effect<S, SE, SR>
) => {
  functions: {
    [k in keyof S as S[k] extends (...args: Array<any>) => Effect<any, any, any> ? k : never]: S[k] extends (
      ...args: infer Args
    ) => Effect<infer A, infer E, infer R>
      ? (...args: Args) => Effect<A, SE | E, SR | R>
      : never
  }
  constants: {
    [k in { [k in keyof S]: k }[keyof S]]: S[k] extends Effect<infer A, infer E, infer R>
      ? Effect<A, SE | E, SR | R>
      : Effect<S[k], SE, SR>
  }
}

Added in v2.0.0

serviceOption

Signature

export declare const serviceOption: <I, S>(tag: Context.Tag<I, S>) => Effect<Option.Option<S>, never, never>

Added in v2.0.0

serviceOptional

Signature

export declare const serviceOptional: <I, S>(tag: Context.Tag<I, S>) => Effect<S, Cause.NoSuchElementException, never>

Added in v2.0.0

updateService

Updates the service with the required service entry.

Signature

export declare const updateService: {
  <T extends Context.Tag<any, any>>(
    tag: T,
    f: (service: Context.Tag.Service<T>) => Context.Tag.Service<T>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R | Context.Tag.Identifier<T>>
  <A, E, R, T extends Context.Tag<any, any>>(
    self: Effect<A, E, R>,
    tag: T,
    f: (service: Context.Tag.Service<T>) => Context.Tag.Service<T>
  ): Effect<A, E, R | Context.Tag.Identifier<T>>
}

Added in v2.0.0

conversions

either

Returns an effect whose failure and success have been lifted into an Either. The resulting effect cannot fail, because the failure case has been exposed as part of the Either success case.

This method is useful for recovering from effects that may fail.

The error parameter of the returned Effect is never, since it is guaranteed the effect does not model failure.

Signature

export declare const either: <A, E, R>(self: Effect<A, E, R>) => Effect<Either.Either<A, E>, never, R>

Added in v2.0.0

exit

Signature

export declare const exit: <A, E, R>(self: Effect<A, E, R>) => Effect<Exit.Exit<A, E>, never, R>

Added in v2.0.0

intoDeferred

Returns an effect that will succeed or fail the specified Deferred based upon the result of the effect. Also synchronizes interruption, so if the provided effect is interrupted, the specified Deferred will be interrupted as well.

Signature

export declare const intoDeferred: {
  <A, E>(deferred: Deferred.Deferred<A, E>): <R>(self: Effect<A, E, R>) => Effect<boolean, never, R>
  <A, E, R>(self: Effect<A, E, R>, deferred: Deferred.Deferred<A, E>): Effect<boolean, never, R>
}

Added in v2.0.0

option

Executes this effect, skipping the error but returning optionally the success.

Signature

export declare const option: <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, never, R>

Added in v2.0.0

delays & timeouts

delay

Returns an effect that is delayed from this effect by the specified Duration.

Signature

export declare const delay: {
  (duration: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(self: Effect<A, E, R>, duration: Duration.DurationInput): Effect<A, E, R>
}

Added in v2.0.0

sleep

Returns an effect that suspends for the specified duration. This method is asynchronous, and does not actually block the fiber executing the effect.

Signature

export declare const sleep: (duration: Duration.DurationInput) => Effect<void>

Added in v2.0.0

timed

Returns a new effect that executes this one and times the execution.

Signature

export declare const timed: <A, E, R>(self: Effect<A, E, R>) => Effect<[Duration.Duration, A], E, R>

Added in v2.0.0

timedWith

A more powerful variation of timed that allows specifying the clock.

Signature

export declare const timedWith: {
  <E1, R1>(
    nanoseconds: Effect<bigint, E1, R1>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<[Duration.Duration, A], E1 | E, R1 | R>
  <A, E, R, E1, R1>(
    self: Effect<A, E, R>,
    nanoseconds: Effect<bigint, E1, R1>
  ): Effect<[Duration.Duration, A], E | E1, R | R1>
}

Added in v2.0.0

timeout

Returns an effect that will timeout this effect, failing with a Cause.TimeoutException if the timeout elapses before the effect has produced a value.

If the timeout elapses without producing a value, the running effect will be safely interrupted.

WARNING: The effect returned by this method will not itself return until the underlying effect is actually interrupted. This leads to more predictable resource utilization. If early return is desired, then instead of using effect.timeout(d), use effect.disconnect.timeout(d), which first disconnects the effect’s interruption signal before performing the timeout, resulting in earliest possible return, before an underlying effect has been successfully interrupted.

Signature

export declare const timeout: {
  (duration: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E | Cause.TimeoutException, R>
  <A, E, R>(self: Effect<A, E, R>, duration: Duration.DurationInput): Effect<A, E | Cause.TimeoutException, R>
}

Added in v2.0.0

timeoutFail

The same as timeout, but instead of producing a None in the event of timeout, it will produce the specified error.

Signature

export declare const timeoutFail: {
  <E1>(options: {
    readonly onTimeout: LazyArg<E1>
    readonly duration: Duration.DurationInput
  }): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E1 | E, R>
  <A, E, R, E1>(
    self: Effect<A, E, R>,
    options: { readonly onTimeout: LazyArg<E1>; readonly duration: Duration.DurationInput }
  ): Effect<A, E | E1, R>
}

Added in v2.0.0

timeoutFailCause

The same as timeout, but instead of producing a None in the event of timeout, it will produce the specified failure.

Signature

export declare const timeoutFailCause: {
  <E1>(options: {
    readonly onTimeout: LazyArg<Cause.Cause<E1>>
    readonly duration: Duration.DurationInput
  }): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E1 | E, R>
  <A, E, R, E1>(
    self: Effect<A, E, R>,
    options: { readonly onTimeout: LazyArg<Cause.Cause<E1>>; readonly duration: Duration.DurationInput }
  ): Effect<A, E | E1, R>
}

Added in v2.0.0

timeoutOption

Returns an effect that will timeout this effect, returning None if the timeout elapses before the effect has produced a value; and returning Some of the produced value otherwise.

If the timeout elapses without producing a value, the running effect will be safely interrupted.

WARNING: The effect returned by this method will not itself return until the underlying effect is actually interrupted. This leads to more predictable resource utilization. If early return is desired, then instead of using effect.timeout(d), use effect.disconnect.timeout(d), which first disconnects the effect’s interruption signal before performing the timeout, resulting in earliest possible return, before an underlying effect has been successfully interrupted.

Signature

export declare const timeoutOption: {
  (duration: Duration.DurationInput): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R>
  <A, E, R>(self: Effect<A, E, R>, duration: Duration.DurationInput): Effect<Option.Option<A>, E, R>
}

Added in v3.1.0

timeoutTo

Returns an effect that will timeout this effect, returning either the default value if the timeout elapses before the effect has produced a value or returning the result of applying the function onSuccess to the success value of the effect.

If the timeout elapses without producing a value, the running effect will be safely interrupted.

Signature

export declare const timeoutTo: {
  <A, B, B1>(options: {
    readonly onTimeout: LazyArg<B1>
    readonly onSuccess: (a: A) => B
    readonly duration: Duration.DurationInput
  }): <E, R>(self: Effect<A, E, R>) => Effect<B | B1, E, R>
  <A, E, R, B1, B>(
    self: Effect<A, E, R>,
    options: {
      readonly onTimeout: LazyArg<B1>
      readonly onSuccess: (a: A) => B
      readonly duration: Duration.DurationInput
    }
  ): Effect<B1 | B, E, R>
}

Added in v2.0.0

do notation

Do

The “do simulation” in allows you to write code in a more declarative style, similar to the “do notation” in other programming languages. It provides a way to define variables and perform operations on them using functions like bind and let.

Here’s how the do simulation works:

  1. Start the do simulation using the Do value
  2. Within the do simulation scope, you can use the bind function to define variables and bind them to Effect values
  3. You can accumulate multiple bind statements to define multiple variables within the scope
  4. Inside the do simulation scope, you can also use the let function to define variables and bind them to simple values

Signature

export declare const Do: Effect<{}, never, never>

Example

import { Effect, pipe } from "effect"

const result = pipe(
  Effect.Do,
  Effect.bind("x", () => Effect.succeed(2)),
  Effect.bind("y", () => Effect.succeed(3)),
  Effect.let("sum", ({ x, y }) => x + y)
)
assert.deepStrictEqual(Effect.runSync(result), { x: 2, y: 3, sum: 5 })

Added in v2.0.0

bind

The “do simulation” in allows you to write code in a more declarative style, similar to the “do notation” in other programming languages. It provides a way to define variables and perform operations on them using functions like bind and let.

Here’s how the do simulation works:

  1. Start the do simulation using the Do value
  2. Within the do simulation scope, you can use the bind function to define variables and bind them to Effect values
  3. You can accumulate multiple bind statements to define multiple variables within the scope
  4. Inside the do simulation scope, you can also use the let function to define variables and bind them to simple values

Signature

export declare const bind: {
  <N extends string, A extends object, B, E2, R2>(
    name: Exclude<N, keyof A>,
    f: (a: A) => Effect<B, E2, R2>
  ): <E1, R1>(self: Effect<A, E1, R1>) => Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E2 | E1, R2 | R1>
  <A extends object, N extends string, E1, R1, B, E2, R2>(
    self: Effect<A, E1, R1>,
    name: Exclude<N, keyof A>,
    f: (a: A) => Effect<B, E2, R2>
  ): Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E1 | E2, R1 | R2>
}

Example

import { Effect, pipe } from "effect"

const result = pipe(
  Effect.Do,
  Effect.bind("x", () => Effect.succeed(2)),
  Effect.bind("y", () => Effect.succeed(3)),
  Effect.let("sum", ({ x, y }) => x + y)
)
assert.deepStrictEqual(Effect.runSync(result), { x: 2, y: 3, sum: 5 })

Added in v2.0.0

bindTo

The “do simulation” in allows you to write code in a more declarative style, similar to the “do notation” in other programming languages. It provides a way to define variables and perform operations on them using functions like bind and let.

Here’s how the do simulation works:

  1. Start the do simulation using the Do value
  2. Within the do simulation scope, you can use the bind function to define variables and bind them to Effect values
  3. You can accumulate multiple bind statements to define multiple variables within the scope
  4. Inside the do simulation scope, you can also use the let function to define variables and bind them to simple values

Signature

export declare const bindTo: {
  <N extends string>(name: N): <A, E, R>(self: Effect<A, E, R>) => Effect<{ [K in N]: A }, E, R>
  <A, E, R, N extends string>(self: Effect<A, E, R>, name: N): Effect<{ [K in N]: A }, E, R>
}

Example

import { Effect, pipe } from "effect"

const result = pipe(
  Effect.Do,
  Effect.bind("x", () => Effect.succeed(2)),
  Effect.bind("y", () => Effect.succeed(3)),
  Effect.let("sum", ({ x, y }) => x + y)
)
assert.deepStrictEqual(Effect.runSync(result), { x: 2, y: 3, sum: 5 })

Added in v2.0.0

let

The “do simulation” in allows you to write code in a more declarative style, similar to the “do notation” in other programming languages. It provides a way to define variables and perform operations on them using functions like bind and let.

Here’s how the do simulation works:

  1. Start the do simulation using the Do value
  2. Within the do simulation scope, you can use the bind function to define variables and bind them to Effect values
  3. You can accumulate multiple bind statements to define multiple variables within the scope
  4. Inside the do simulation scope, you can also use the let function to define variables and bind them to simple values

Signature

export declare const let: {
  <N extends string, A extends object, B>(
    name: Exclude<N, keyof A>,
    f: (a: A) => B
  ): <E, R>(self: Effect<A, E, R>) => Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>
  <A extends object, N extends string, E, R, B>(
    self: Effect<A, E, R>,
    name: Exclude<N, keyof A>,
    f: (a: A) => B
  ): Effect<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, E, R>
}

Example

import { Effect, pipe } from "effect"

const result = pipe(
  Effect.Do,
  Effect.bind("x", () => Effect.succeed(2)),
  Effect.bind("y", () => Effect.succeed(3)),
  Effect.let("sum", ({ x, y }) => x + y)
)
assert.deepStrictEqual(Effect.runSync(result), { x: 2, y: 3, sum: 5 })

Added in v2.0.0

error handling

Retry (namespace)

Added in v2.0.0

Options (interface)

Signature

export interface Options<E> {
  while?: ((error: E) => boolean | Effect<boolean, any, any>) | undefined
  until?: ((error: E) => boolean | Effect<boolean, any, any>) | undefined
  times?: number | undefined
  schedule?: Schedule.Schedule<any, E, any> | undefined
}

Added in v2.0.0

Return (type alias)

Signature

export type Return<R, E, A, O extends Options<E>> =
  Effect<
    A,
    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer _R> }
        ? E
        : O extends { until: Refinement<E, infer E2> }
          ? E2
          : E)
    | (O extends { while: (...args: Array<any>) => Effect<infer _A, infer E, infer _R> } ? E : never)
    | (O extends { until: (...args: Array<any>) => Effect<infer _A, infer E, infer _R> } ? E : never),
    | R
    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer R> } ? R : never)
    | (O extends { while: (...args: Array<any>) => Effect<infer _A, infer _E, infer R> } ? R : never)
    | (O extends { until: (...args: Array<any>) => Effect<infer _A, infer _E, infer R> } ? R : never)
  > extends infer Z
    ? Z
    : never

Added in v2.0.0

catch

Recovers from specified error.

Signature

export declare const catch: { <N extends keyof E, K extends E[N] & string, E, A1, E1, R1>(discriminator: N, options: { readonly failure: K; readonly onFailure: (error: Extract<E, { [n in N]: K; }>) => Effect<A1, E1, R1>; }): <A, R>(self: Effect<A, E, R>) => Effect<A1 | A, E1 | Exclude<E, { [n in N]: K; }>, R1 | R>; <A, E, R, N extends keyof E, K extends E[N] & string, A1, E1, R1>(self: Effect<A, E, R>, discriminator: N, options: { readonly failure: K; readonly onFailure: (error: Extract<E, { [n in N]: K; }>) => Effect<A1, E1, R1>; }): Effect<A | A1, E1 | Exclude<E, { [n in N]: K; }>, R | R1>; }

Added in v2.0.0

catchAll

Recovers from all recoverable errors.

Note: that Effect.catchAll will not recover from unrecoverable defects. To recover from both recoverable and unrecoverable errors use Effect.catchAllCause.

Signature

export declare const catchAll: {
  <E, A2, E2, R2>(f: (e: E) => Effect<A2, E2, R2>): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2, R2 | R>
  <A, E, R, A2, E2, R2>(self: Effect<A, E, R>, f: (e: E) => Effect<A2, E2, R2>): Effect<A | A2, E2, R | R2>
}

Added in v2.0.0

catchAllCause

Recovers from both recoverable and unrecoverable errors.

See sandbox, mapErrorCause for other functions that can recover from defects.

Signature

export declare const catchAllCause: {
  <E, A2, E2, R2>(
    f: (cause: Cause.Cause<E>) => Effect<A2, E2, R2>
  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2, R2 | R>
  <A, E, R, A2, E2, R2>(
    self: Effect<A, E, R>,
    f: (cause: Cause.Cause<E>) => Effect<A2, E2, R2>
  ): Effect<A | A2, E2, R | R2>
}

Added in v2.0.0

catchAllDefect

Recovers from all defects with provided function.

WARNING: There is no sensible way to recover from defects. This method should be used only at the boundary between Effect and an external system, to transmit information on a defect for diagnostic or explanatory purposes.

Signature

export declare const catchAllDefect: {
  <A2, E2, R2>(
    f: (defect: unknown) => Effect<A2, E2, R2>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | E, R2 | R>
  <A, E, R, A2, E2, R2>(
    self: Effect<A, E, R>,
    f: (defect: unknown) => Effect<A2, E2, R2>
  ): Effect<A | A2, E | E2, R | R2>
}

Added in v2.0.0

catchIf

Recovers from errors that match the given predicate.

Signature

export declare const catchIf: {
  <E, EB extends E, A2, E2, R2>(
    refinement: Refinement<NoInfer<E>, EB>,
    f: (e: EB) => Effect<A2, E2, R2>
  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | Exclude<E, EB>, R2 | R>
  <E, A2, E2, R2>(
    predicate: Predicate<NoInfer<E>>,
    f: (e: NoInfer<E>) => Effect<A2, E2, R2>
  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E | E2, R2 | R>
  <A, E, R, EB extends E, A2, E2, R2>(
    self: Effect<A, E, R>,
    refinement: Refinement<E, EB>,
    f: (e: EB) => Effect<A2, E2, R2>
  ): Effect<A | A2, E2 | Exclude<E, EB>, R | R2>
  <A, E, R, A2, E2, R2>(
    self: Effect<A, E, R>,
    predicate: Predicate<E>,
    f: (e: E) => Effect<A2, E2, R2>
  ): Effect<A | A2, E | E2, R | R2>
}

Added in v2.0.0

catchSome

Recovers from some or all of the error cases.

Signature

export declare const catchSome: {
  <E, A2, E2, R2>(
    pf: (e: NoInfer<E>) => Option.Option<Effect<A2, E2, R2>>
  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E | E2, R2 | R>
  <A, E, R, A2, E2, R2>(
    self: Effect<A, E, R>,
    pf: (e: NoInfer<E>) => Option.Option<Effect<A2, E2, R2>>
  ): Effect<A | A2, E | E2, R | R2>
}

Added in v2.0.0

catchSomeCause

Recovers from some or all of the error cases with provided cause.

Signature

export declare const catchSomeCause: {
  <E, A2, E2, R2>(
    f: (cause: Cause.Cause<NoInfer<E>>) => Option.Option<Effect<A2, E2, R2>>
  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E | E2, R2 | R>
  <A, E, R, A2, E2, R2>(
    self: Effect<A, E, R>,
    f: (cause: Cause.Cause<NoInfer<E>>) => Option.Option<Effect<A2, E2, R2>>
  ): Effect<A | A2, E | E2, R | R2>
}

Added in v2.0.0

catchSomeDefect

Recovers from some or all of the defects with provided partial function.

WARNING: There is no sensible way to recover from defects. This method should be used only at the boundary between Effect and an external system, to transmit information on a defect for diagnostic or explanatory purposes.

Signature

export declare const catchSomeDefect: {
  <A2, E2, R2>(
    pf: (defect: unknown) => Option.Option<Effect<A2, E2, R2>>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | E, R2 | R>
  <A, E, R, A2, E2, R2>(
    self: Effect<A, E, R>,
    pf: (defect: unknown) => Option.Option<Effect<A2, E2, R2>>
  ): Effect<A | A2, E | E2, R | R2>
}

Added in v2.0.0

catchTag

Recovers from the specified tagged error.

Signature

export declare const catchTag: {
  <K extends E extends { _tag: string } ? E["_tag"] : never, E, A1, E1, R1>(
    k: K,
    f: (e: Extract<E, { _tag: K }>) => Effect<A1, E1, R1>
  ): <A, R>(self: Effect<A, E, R>) => Effect<A1 | A, E1 | Exclude<E, { _tag: K }>, R1 | R>
  <A, E, R, K extends E extends { _tag: string } ? E["_tag"] : never, R1, E1, A1>(
    self: Effect<A, E, R>,
    k: K,
    f: (e: Extract<E, { _tag: K }>) => Effect<A1, E1, R1>
  ): Effect<A | A1, E1 | Exclude<E, { _tag: K }>, R | R1>
}

Added in v2.0.0

catchTags

Recovers from the specified tagged errors.

Signature

export declare const catchTags: {
  <
    E,
    Cases extends {
      [K in Extract<E, { _tag: string }>["_tag"]]+?:
        | ((error: Extract<E, { _tag: K }>) => Effect<any, any, any>)
        | undefined
    } & (unknown extends E ? {} : { [K in Exclude<keyof Cases, Extract<E, { _tag: string }>["_tag"]>]: never })
  >(
    cases: Cases
  ): <A, R>(
    self: Effect<A, E, R>
  ) => Effect<
    | A
    | {
        [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<infer A, any, any> ? A : never
      }[keyof Cases],
    | Exclude<E, { _tag: keyof Cases }>
    | {
        [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<any, infer E, any> ? E : never
      }[keyof Cases],
    | R
    | {
        [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<any, any, infer R> ? R : never
      }[keyof Cases]
  >
  <
    R,
    E,
    A,
    Cases extends {
      [K in Extract<E, { _tag: string }>["_tag"]]+?:
        | ((error: Extract<E, { _tag: K }>) => Effect<any, any, any>)
        | undefined
    } & (unknown extends E ? {} : { [K in Exclude<keyof Cases, Extract<E, { _tag: string }>["_tag"]>]: never })
  >(
    self: Effect<A, E, R>,
    cases: Cases
  ): Effect<
    | A
    | {
        [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<infer A, any, any> ? A : never
      }[keyof Cases],
    | Exclude<E, { _tag: keyof Cases }>
    | {
        [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<any, infer E, any> ? E : never
      }[keyof Cases],
    | R
    | {
        [K in keyof Cases]: Cases[K] extends (...args: Array<any>) => Effect<any, any, infer R> ? R : never
      }[keyof Cases]
  >
}

Added in v2.0.0

cause

Returns an effect that succeeds with the cause of failure of this effect, or Cause.empty if the effect did succeed.

Signature

export declare const cause: <A, E, R>(self: Effect<A, E, R>) => Effect<Cause.Cause<E>, never, R>

Added in v2.0.0

eventually

Returns an effect that ignores errors and runs repeatedly until it eventually succeeds.

Signature

export declare const eventually: <A, E, R>(self: Effect<A, E, R>) => Effect<A, never, R>

Added in v2.0.0

ignore

Returns a new effect that ignores the success or failure of this effect.

Signature

export declare const ignore: <A, E, R>(self: Effect<A, E, R>) => Effect<void, never, R>

Added in v2.0.0

ignoreLogged

Returns a new effect that ignores the success or failure of this effect, but which also logs failures at the Debug level, just in case the failure turns out to be important.

Signature

export declare const ignoreLogged: <A, E, R>(self: Effect<A, E, R>) => Effect<void, never, R>

Added in v2.0.0

parallelErrors

Exposes all parallel errors in a single call.

Signature

export declare const parallelErrors: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E[], R>

Added in v2.0.0

retry

Retries according to the options provided

Signature

export declare const retry: {
  <E, O extends Retry.Options<E>>(
    options: O
  ): <A, R>(
    self: Effect<A, E, R>
  ) => Effect<
    A,
    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer _R> }
        ? E
        : O extends { until: Refinement<E, infer E2 extends E> }
          ? E2
          : E)
    | (O extends { while: (...args: any[]) => Effect<infer _A, infer E, infer _R> } ? E : never)
    | (O extends { until: (...args: any[]) => Effect<infer _A, infer E, infer _R> } ? E : never),
    | R
    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer R> } ? R : never)
    | (O extends { while: (...args: any[]) => Effect<infer _A, infer _E, infer R> } ? R : never)
    | (O extends { until: (...args: any[]) => Effect<infer _A, infer _E, infer R> } ? R : never)
  >
  <B, E, R1>(policy: Schedule.Schedule<B, NoInfer<E>, R1>): <A, R>(self: Effect<A, E, R>) => Effect<A, E, R1 | R>
  <A, E, R, O extends Retry.Options<E>>(
    self: Effect<A, E, R>,
    options: O
  ): Effect<
    A,
    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer _R> }
        ? E
        : O extends { until: Refinement<E, infer E2 extends E> }
          ? E2
          : E)
    | (O extends { while: (...args: any[]) => Effect<infer _A, infer E, infer _R> } ? E : never)
    | (O extends { until: (...args: any[]) => Effect<infer _A, infer E, infer _R> } ? E : never),
    | R
    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer R> } ? R : never)
    | (O extends { while: (...args: any[]) => Effect<infer _A, infer _E, infer R> } ? R : never)
    | (O extends { until: (...args: any[]) => Effect<infer _A, infer _E, infer R> } ? R : never)
  >
  <A, E, R, B, R1>(self: Effect<A, E, R>, policy: Schedule.Schedule<B, E, R1>): Effect<A, E, R | R1>
}

Added in v2.0.0

retryOrElse

Retries with the specified schedule, until it fails, and then both the value produced by the schedule together with the last error are passed to the recovery function.

Signature

export declare const retryOrElse: {
  <A1, E, R1, A2, E2, R2>(
    policy: Schedule.Schedule<A1, NoInfer<E>, R1>,
    orElse: (e: NoInfer<E>, out: A1) => Effect<A2, E2, R2>
  ): <A, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2, R1 | R2 | R>
  <A, E, R, A1, R1, A2, E2, R2>(
    self: Effect<A, E, R>,
    policy: Schedule.Schedule<A1, NoInfer<E>, R1>,
    orElse: (e: NoInfer<E>, out: A1) => Effect<A2, E2, R2>
  ): Effect<A | A2, E2, R | R1 | R2>
}

Added in v2.0.0

sandbox

Exposes the full Cause of failure for the specified effect.

Signature

export declare const sandbox: <A, E, R>(self: Effect<A, E, R>) => Effect<A, Cause.Cause<E>, R>

Added in v2.0.0

try

Imports a synchronous side-effect into a pure Effect value, translating any thrown exceptions into typed failed effects creating with Effect.fail.

Signature

export declare const try: { <A, E>(options: { readonly try: LazyArg<A>; readonly catch: (error: unknown) => E; }): Effect<A, E, never>; <A>(evaluate: LazyArg<A>): Effect<A, Cause.UnknownException, never>; }

Added in v2.0.0

tryMap

Returns an effect whose success is mapped by the specified side effecting try function, translating any promise rejections into typed failed effects via the catch function.

Signature

export declare const tryMap: {
  <A, B, E1>(options: {
    readonly try: (a: A) => B
    readonly catch: (error: unknown) => E1
  }): <E, R>(self: Effect<A, E, R>) => Effect<B, E1 | E, R>
  <A, E, R, B, E1>(
    self: Effect<A, E, R>,
    options: { readonly try: (a: A) => B; readonly catch: (error: unknown) => E1 }
  ): Effect<B, E | E1, R>
}

Added in v2.0.0

tryMapPromise

Returns an effect whose success is mapped by the specified side effecting try function, translating any promise rejections into typed failed effects via the catch function.

An optional AbortSignal can be provided to allow for interruption of the wrapped Promise api.

Signature

export declare const tryMapPromise: {
  <A, B, E1>(options: {
    readonly try: (a: A, signal: AbortSignal) => PromiseLike<B>
    readonly catch: (error: unknown) => E1
  }): <E, R>(self: Effect<A, E, R>) => Effect<B, E1 | E, R>
  <A, E, R, B, E1>(
    self: Effect<A, E, R>,
    options: { readonly try: (a: A, signal: AbortSignal) => PromiseLike<B>; readonly catch: (error: unknown) => E1 }
  ): Effect<B, E | E1, R>
}

Added in v2.0.0

tryPromise

Create an Effect that when executed will construct promise and wait for its result, errors will produce failure as unknown.

An optional AbortSignal can be provided to allow for interruption of the wrapped Promise api.

Signature

export declare const tryPromise: {
  <A, E>(options: {
    readonly try: (signal: AbortSignal) => PromiseLike<A>
    readonly catch: (error: unknown) => E
  }): Effect<A, E, never>
  <A>(try_: (signal: AbortSignal) => PromiseLike<A>): Effect<A, Cause.UnknownException, never>
}

Added in v2.0.0

unsandbox

The inverse operation sandbox(effect)

Terminates with exceptions on the Left side of the Either error, if it exists. Otherwise extracts the contained Effect<A, E, R>

Signature

export declare const unsandbox: <A, E, R>(self: Effect<A, Cause.Cause<E>, R>) => Effect<A, E, R>

Added in v2.0.0

execution

runCallback

Signature

export declare const runCallback: <A, E>(
  effect: Effect<A, E, never>,
  options?: Runtime.RunCallbackOptions<A, E> | undefined
) => Runtime.Cancel<A, E>

Added in v2.0.0

runFork

Signature

export declare const runFork: <A, E>(
  effect: Effect<A, E, never>,
  options?: Runtime.RunForkOptions
) => Fiber.RuntimeFiber<A, E>

Added in v2.0.0

runPromise

Runs an Effect workflow, returning a Promise which resolves with the result of the workflow or rejects with an error.

Signature

export declare const runPromise: <A, E>(
  effect: Effect<A, E, never>,
  options?: { readonly signal?: AbortSignal } | undefined
) => Promise<A>

Added in v2.0.0

runPromiseExit

Runs an Effect workflow, returning a Promise which resolves with the Exit value of the workflow.

Signature

export declare const runPromiseExit: <A, E>(
  effect: Effect<A, E, never>,
  options?: { readonly signal?: AbortSignal } | undefined
) => Promise<Exit.Exit<A, E>>

Added in v2.0.0

runSync

Signature

export declare const runSync: <A, E>(effect: Effect<A, E, never>) => A

Added in v2.0.0

runSyncExit

Signature

export declare const runSyncExit: <A, E>(effect: Effect<A, E, never>) => Exit.Exit<A, E>

Added in v2.0.0

fiber refs

getFiberRefs

Returns a collection of all FiberRef values for the fiber running this effect.

Signature

export declare const getFiberRefs: Effect<FiberRefs.FiberRefs, never, never>

Added in v2.0.0

inheritFiberRefs

Inherits values from all FiberRef instances into current fiber.

Signature

export declare const inheritFiberRefs: (childFiberRefs: FiberRefs.FiberRefs) => Effect<void>

Added in v2.0.0

locally

Signature

export declare const locally: {
  <A>(self: FiberRef.FiberRef<A>, value: A): <B, E, R>(use: Effect<B, E, R>) => Effect<B, E, R>
  <B, E, R, A>(use: Effect<B, E, R>, self: FiberRef.FiberRef<A>, value: A): Effect<B, E, R>
}

Added in v2.0.0

locallyScoped

Signature

export declare const locallyScoped: {
  <A>(value: A): (self: FiberRef.FiberRef<A>) => Effect<void, never, Scope.Scope>
  <A>(self: FiberRef.FiberRef<A>, value: A): Effect<void, never, Scope.Scope>
}

Added in v2.0.0

locallyScopedWith

Signature

export declare const locallyScopedWith: {
  <A>(f: (a: A) => A): (self: FiberRef.FiberRef<A>) => Effect<void, never, Scope.Scope>
  <A>(self: FiberRef.FiberRef<A>, f: (a: A) => A): Effect<void, never, Scope.Scope>
}

Added in v2.0.0

locallyWith

Signature

export declare const locallyWith: {
  <A>(self: FiberRef.FiberRef<A>, f: (a: A) => A): <B, E, R>(use: Effect<B, E, R>) => Effect<B, E, R>
  <B, E, R, A>(use: Effect<B, E, R>, self: FiberRef.FiberRef<A>, f: (a: A) => A): Effect<B, E, R>
}

Added in v2.0.0

patchFiberRefs

Applies the specified changes to the FiberRef values for the fiber running this workflow.

Signature

export declare const patchFiberRefs: (patch: FiberRefsPatch.FiberRefsPatch) => Effect<void>

Added in v2.0.0

setFiberRefs

Sets the FiberRef values for the fiber running this effect to the values in the specified collection of FiberRef values.

Signature

export declare const setFiberRefs: (fiberRefs: FiberRefs.FiberRefs) => Effect<void>

Added in v2.0.0

updateFiberRefs

Updates the FiberRef values for the fiber running this effect using the specified function.

Signature

export declare const updateFiberRefs: (
  f: (fiberId: FiberId.Runtime, fiberRefs: FiberRefs.FiberRefs) => FiberRefs.FiberRefs
) => Effect<void>

Added in v2.0.0

filtering & conditionals

filterOrDie

Filter the specified effect with the provided function, dying with specified defect if the predicate fails.

Signature

export declare const filterOrDie: {
  <A, B extends A>(
    refinement: Refinement<NoInfer<A>, B>,
    orDieWith: (a: NoInfer<A>) => unknown
  ): <E, R>(self: Effect<A, E, R>) => Effect<B, E, R>
  <A>(
    predicate: Predicate<NoInfer<A>>,
    orDieWith: (a: NoInfer<A>) => unknown
  ): <E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R, B extends A>(
    self: Effect<A, E, R>,
    refinement: Refinement<A, B>,
    orDieWith: (a: A) => unknown
  ): Effect<B, E, R>
  <A, E, R>(self: Effect<A, E, R>, predicate: Predicate<A>, orDieWith: (a: A) => unknown): Effect<A, E, R>
}

Added in v2.0.0

filterOrDieMessage

Filter the specified effect with the provided function, dying with specified message if the predicate fails.

Signature

export declare const filterOrDieMessage: {
  <A, B extends A>(
    refinement: Refinement<NoInfer<A>, B>,
    message: string
  ): <E, R>(self: Effect<A, E, R>) => Effect<B, E, R>
  <A>(predicate: Predicate<NoInfer<A>>, message: string): <E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R, B extends A>(self: Effect<A, E, R>, refinement: Refinement<A, B>, message: string): Effect<B, E, R>
  <A, E, R>(self: Effect<A, E, R>, predicate: Predicate<A>, message: string): Effect<A, E, R>
}

Added in v2.0.0

filterOrElse

Filters the specified effect with the provided function returning the value of the effect if it is successful, otherwise returns the value of orElse.

Signature

export declare const filterOrElse: {
  <A, B extends A, C, E2, R2>(
    refinement: Refinement<NoInfer<A>, B>,
    orElse: (a: NoInfer<A>) => Effect<C, E2, R2>
  ): <E, R>(self: Effect<A, E, R>) => Effect<B | C, E2 | E, R2 | R>
  <A, B, E2, R2>(
    predicate: Predicate<NoInfer<A>>,
    orElse: (a: NoInfer<A>) => Effect<B, E2, R2>
  ): <E, R>(self: Effect<A, E, R>) => Effect<A | B, E2 | E, R2 | R>
  <A, E, R, B extends A, C, E2, R2>(
    self: Effect<A, E, R>,
    refinement: Refinement<A, B>,
    orElse: (a: A) => Effect<C, E2, R2>
  ): Effect<B | C, E | E2, R | R2>
  <A, E, R, B, E2, R2>(
    self: Effect<A, E, R>,
    predicate: Predicate<A>,
    orElse: (a: A) => Effect<B, E2, R2>
  ): Effect<A | B, E | E2, R | R2>
}

Added in v2.0.0

filterOrFail

Filter the specified effect with the provided function, failing with specified error if the predicate fails.

In addition to the filtering capabilities discussed earlier, you have the option to further refine and narrow down the type of the success channel by providing a user-defined type guard. Let’s explore this concept through an example:

Signature

export declare const filterOrFail: {
  <A, B extends A, E2>(
    refinement: Refinement<NoInfer<A>, B>,
    orFailWith: (a: NoInfer<A>) => E2
  ): <E, R>(self: Effect<A, E, R>) => Effect<B, E2 | E, R>
  <A, E2>(
    predicate: Predicate<NoInfer<A>>,
    orFailWith: (a: NoInfer<A>) => E2
  ): <E, R>(self: Effect<A, E, R>) => Effect<A, E2 | E, R>
  <A, B extends A>(
    refinement: Refinement<NoInfer<A>, B>
  ): <E, R>(self: Effect<A, E, R>) => Effect<B, Cause.NoSuchElementException | E, R>
  <A>(predicate: Predicate<NoInfer<A>>): <E, R>(self: Effect<A, E, R>) => Effect<A, Cause.NoSuchElementException | E, R>
  <A, E, R, B extends A, E2>(
    self: Effect<A, E, R>,
    refinement: Refinement<A, B>,
    orFailWith: (a: A) => E2
  ): Effect<B, E | E2, R>
  <A, E, R, E2>(self: Effect<A, E, R>, predicate: Predicate<A>, orFailWith: (a: A) => E2): Effect<A, E | E2, R>
  <A, E, R, B extends A>(
    self: Effect<A, E, R>,
    refinement: Refinement<A, B>
  ): Effect<B, Cause.NoSuchElementException | E, R>
  <A, E, R>(self: Effect<A, E, R>, predicate: Predicate<A>): Effect<A, Cause.NoSuchElementException | E, R>
}

Example

import { Effect, pipe } from "effect"

// Define a user interface
interface User {
  readonly name: string
}

// Assume an asynchronous authentication function
declare const auth: () => Promise<User | null>

const program = pipe(
  Effect.promise(() => auth()),
  Effect.filterOrFail(
    // Define a guard to narrow down the type
    (user): user is User => user !== null,
    () => new Error("Unauthorized")
  ),
  Effect.map((user) => user.name) // The 'user' here has type `User`, not `User | null`
)

Added in v2.0.0

if

Runs onTrue if the result of self is true and onFalse otherwise.

Signature

export declare const if: { <A1, E1, R1, A2, E2, R2>(options: { readonly onTrue: LazyArg<Effect<A1, E1, R1>>; readonly onFalse: LazyArg<Effect<A2, E2, R2>>; }): <E = never, R = never>(self: boolean | Effect<boolean, E, R>) => Effect<A1 | A2, E1 | E2 | E, R1 | R2 | R>; <A1, E1, R1, A2, E2, R2, E = never, R = never>(self: boolean | Effect<boolean, E, R>, options: { readonly onTrue: LazyArg<Effect<A1, E1, R1>>; readonly onFalse: LazyArg<Effect<A2, E2, R2>>; }): Effect<A1 | A2, E1 | E2 | E, R1 | R2 | R>; }

Added in v2.0.0

unless

The moral equivalent of if (!p) exp.

Signature

export declare const unless: {
  (condition: LazyArg<boolean>): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R>
  <A, E, R>(self: Effect<A, E, R>, condition: LazyArg<boolean>): Effect<Option.Option<A>, E, R>
}

Added in v2.0.0

unlessEffect

The moral equivalent of if (!p) exp when p has side-effects.

Signature

export declare const unlessEffect: {
  <E2, R2>(
    condition: Effect<boolean, E2, R2>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E2 | E, R2 | R>
  <A, E, R, E2, R2>(self: Effect<A, E, R>, condition: Effect<boolean, E2, R2>): Effect<Option.Option<A>, E | E2, R | R2>
}

Added in v2.0.0

when

The moral equivalent of if (p) exp.

Signature

export declare const when: {
  (condition: LazyArg<boolean>): <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R>
  <A, E, R>(self: Effect<A, E, R>, condition: LazyArg<boolean>): Effect<Option.Option<A>, E, R>
}

Added in v2.0.0

whenEffect

Signature

export declare const whenEffect: {
  <E, R>(
    condition: Effect<boolean, E, R>
  ): <A, E2, R2>(effect: Effect<A, E2, R2>) => Effect<Option.Option<A>, E | E2, R | R2>
  <A, E2, R2, E, R>(self: Effect<A, E2, R2>, condition: Effect<boolean, E, R>): Effect<Option.Option<A>, E2 | E, R2 | R>
}

Added in v2.0.0

whenFiberRef

Executes this workflow when value of the specified FiberRef satisfies the predicate.

Signature

export declare const whenFiberRef: {
  <S>(
    fiberRef: FiberRef.FiberRef<S>,
    predicate: Predicate<S>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<[S, Option.Option<A>], E, R>
  <A, E, R, S>(
    self: Effect<A, E, R>,
    fiberRef: FiberRef.FiberRef<S>,
    predicate: Predicate<S>
  ): Effect<[S, Option.Option<A>], E, R>
}

Added in v2.0.0

whenRef

Executes this workflow when the value of the Ref satisfies the predicate.

Signature

export declare const whenRef: {
  <S>(ref: Ref.Ref<S>, predicate: Predicate<S>): <A, E, R>(self: Effect<A, E, R>) => Effect<[S, Option.Option<A>], E, R>
  <A, E, R, S>(self: Effect<A, E, R>, ref: Ref.Ref<S>, predicate: Predicate<S>): Effect<[S, Option.Option<A>], E, R>
}

Added in v2.0.0

getters & folding

isFailure

Returns true if this effect is a failure, false otherwise.

Signature

export declare const isFailure: <A, E, R>(self: Effect<A, E, R>) => Effect<boolean, never, R>

Added in v2.0.0

isSuccess

Returns true if this effect is a success, false otherwise.

Signature

export declare const isSuccess: <A, E, R>(self: Effect<A, E, R>) => Effect<boolean, never, R>

Added in v2.0.0

match

Folds over the failure value or the success value to yield an effect that does not fail, but succeeds with the value returned by the left or right function passed to match.

Signature

export declare const match: {
  <E, A2, A, A3>(options: {
    readonly onFailure: (error: E) => A2
    readonly onSuccess: (value: A) => A3
  }): <R>(self: Effect<A, E, R>) => Effect<A2 | A3, never, R>
  <A, E, R, A2, A3>(
    self: Effect<A, E, R>,
    options: { readonly onFailure: (error: E) => A2; readonly onSuccess: (value: A) => A3 }
  ): Effect<A2 | A3, never, R>
}

Added in v2.0.0

matchCause

Signature

export declare const matchCause: {
  <E, A2, A, A3>(options: {
    readonly onFailure: (cause: Cause.Cause<E>) => A2
    readonly onSuccess: (a: A) => A3
  }): <R>(self: Effect<A, E, R>) => Effect<A2 | A3, never, R>
  <A, E, R, A2, A3>(
    self: Effect<A, E, R>,
    options: { readonly onFailure: (cause: Cause.Cause<E>) => A2; readonly onSuccess: (a: A) => A3 }
  ): Effect<A2 | A3, never, R>
}

Added in v2.0.0

matchCauseEffect

Signature

export declare const matchCauseEffect: {
  <E, A2, E2, R2, A, A3, E3, R3>(options: {
    readonly onFailure: (cause: Cause.Cause<E>) => Effect<A2, E2, R2>
    readonly onSuccess: (a: A) => Effect<A3, E3, R3>
  }): <R>(self: Effect<A, E, R>) => Effect<A2 | A3, E2 | E3, R2 | R3 | R>
  <A, E, R, A2, E2, R2, A3, E3, R3>(
    self: Effect<A, E, R>,
    options: {
      readonly onFailure: (cause: Cause.Cause<E>) => Effect<A2, E2, R2>
      readonly onSuccess: (a: A) => Effect<A3, E3, R3>
    }
  ): Effect<A2 | A3, E2 | E3, R | R2 | R3>
}

Added in v2.0.0

matchEffect

Signature

export declare const matchEffect: {
  <E, A2, E2, R2, A, A3, E3, R3>(options: {
    readonly onFailure: (e: E) => Effect<A2, E2, R2>
    readonly onSuccess: (a: A) => Effect<A3, E3, R3>
  }): <R>(self: Effect<A, E, R>) => Effect<A2 | A3, E2 | E3, R2 | R3 | R>
  <A, E, R, A2, E2, R2, A3, E3, R3>(
    self: Effect<A, E, R>,
    options: { readonly onFailure: (e: E) => Effect<A2, E2, R2>; readonly onSuccess: (a: A) => Effect<A3, E3, R3> }
  ): Effect<A2 | A3, E2 | E3, R | R2 | R3>
}

Added in v2.0.0

interruption

allowInterrupt

This function checks if any fibers are attempting to interrupt the current fiber, and if so, performs self-interruption.

Note that this allows for interruption to occur in uninterruptible regions.

Signature

export declare const allowInterrupt: Effect<void, never, never>

Added in v2.0.0

checkInterruptible

Checks the interrupt status, and produces the effect returned by the specified callback.

Signature

export declare const checkInterruptible: <A, E, R>(f: (isInterruptible: boolean) => Effect<A, E, R>) => Effect<A, E, R>

Added in v2.0.0

disconnect

Returns an effect whose interruption will be disconnected from the fiber’s own interruption, being performed in the background without slowing down the fiber’s interruption.

This method is useful to create “fast interrupting” effects. For example, if you call this on a bracketed effect, then even if the effect is “stuck” in acquire or release, its interruption will return immediately, while the acquire / release are performed in the background.

See timeout and race for other applications.

Signature

export declare const disconnect: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>

Added in v2.0.0

interrupt

Signature

export declare const interrupt: Effect<never, never, never>

Added in v2.0.0

interruptWith

Signature

export declare const interruptWith: (fiberId: FiberId.FiberId) => Effect<never>

Added in v2.0.0

interruptible

Signature

export declare const interruptible: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>

Added in v2.0.0

interruptibleMask

Signature

export declare const interruptibleMask: <A, E, R>(
  f: (restore: <AX, EX, RX>(effect: Effect<AX, EX, RX>) => Effect<AX, EX, RX>) => Effect<A, E, R>
) => Effect<A, E, R>

Added in v2.0.0

onInterrupt

Signature

export declare const onInterrupt: {
  <X, R2>(
    cleanup: (interruptors: HashSet.HashSet<FiberId.FiberId>) => Effect<X, never, R2>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R2 | R>
  <A, E, R, X, R2>(
    self: Effect<A, E, R>,
    cleanup: (interruptors: HashSet.HashSet<FiberId.FiberId>) => Effect<X, never, R2>
  ): Effect<A, E, R | R2>
}

Added in v2.0.0

uninterruptible

Signature

export declare const uninterruptible: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>

Added in v2.0.0

uninterruptibleMask

Signature

export declare const uninterruptibleMask: <A, E, R>(
  f: (restore: <AX, EX, RX>(effect: Effect<AX, EX, RX>) => Effect<AX, EX, RX>) => Effect<A, E, R>
) => Effect<A, E, R>

Added in v2.0.0

lifting

liftPredicate

Transforms a Predicate function into an Effect returning the input value if the predicate returns true or failing with specified error if the predicate fails

Signature

export declare const liftPredicate: {
  <A, B extends A, E>(
    refinement: Refinement<NoInfer<A>, B>,
    orFailWith: (a: NoInfer<A>) => E
  ): (a: A) => Effect<B, E, never>
  <A, E>(predicate: Predicate<NoInfer<A>>, orFailWith: (a: NoInfer<A>) => E): (a: A) => Effect<A, E, never>
  <A, E, B extends A>(self: A, refinement: Refinement<A, B>, orFailWith: (a: A) => E): Effect<B, E, never>
  <A, E>(self: A, predicate: Predicate<NoInfer<A>>, orFailWith: (a: NoInfer<A>) => E): Effect<A, E, never>
}

Example

import { Effect } from "effect"

const isPositive = (n: number): boolean => n > 0

// succeeds with `1`
Effect.liftPredicate(1, isPositive, (n) => `${n} is not positive`)

// fails with `"0 is not positive"`
Effect.liftPredicate(0, isPositive, (n) => `${n} is not positive`)

Added in v3.4.0

logging

annotateLogs

Augments log outputs by appending custom annotations to log entries generated within an effect. This function provides a way to add more context and detail to log messages, making them more informative and easier to trace.

Signature

export declare const annotateLogs: {
  (key: string, value: unknown): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>
  (values: Record<string, unknown>): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(effect: Effect<A, E, R>, key: string, value: unknown): Effect<A, E, R>
  <A, E, R>(effect: Effect<A, E, R>, values: Record<string, unknown>): Effect<A, E, R>
}

Example

import { Effect } from "effect"

const program = Effect.gen(function* () {
  yield* Effect.log("message1")
  yield* Effect.log("message2")
}).pipe(Effect.annotateLogs("key", "value")) // Annotation as key/value pair

// Effect.runFork(program)
// timestamp=... level=INFO fiber=#0 message=message1 key=value
// timestamp=... level=INFO fiber=#0 message=message2 key=value

Added in v2.0.0

annotateLogsScoped

Applies log annotations with a limited scope, restricting their appearance to specific sections of your effect computations. Use Effect.annotateLogsScoped to add metadata to logs that only appear within a defined Scope, making it easier to manage context-specific logging.

Signature

export declare const annotateLogsScoped: {
  (key: string, value: unknown): Effect<void, never, Scope.Scope>
  (values: Record<string, unknown>): Effect<void, never, Scope.Scope>
}

Example

import { Effect } from "effect"

const program = Effect.gen(function* () {
  yield* Effect.log("no annotations")
  yield* Effect.annotateLogsScoped({ key: "value" })
  yield* Effect.log("message1") // Annotation is applied to this log
  yield* Effect.log("message2") // Annotation is applied to this log
}).pipe(Effect.scoped, Effect.andThen(Effect.log("no annotations again")))

// Effect.runFork(program)
// timestamp=... level=INFO fiber=#0 message="no annotations"
// timestamp=... level=INFO fiber=#0 message=message1 key=value
// timestamp=... level=INFO fiber=#0 message=message2 key=value
// timestamp=... level=INFO fiber=#0 message="no annotations again"

Added in v3.1.0

log

Logs one or more messages or error causes at the current log level, which is INFO by default. This function allows logging multiple items at once and can include detailed error information using Cause instances.

To adjust the log level, use the Logger.withMinimumLogLevel function.

Signature

export declare const log: (...message: ReadonlyArray<any>) => Effect<void, never, never>

Example

import { Cause, Effect } from "effect"

const program = Effect.log("message1", "message2", Cause.die("Oh no!"), Cause.die("Oh uh!"))

// Effect.runFork(program)
// Output:
// timestamp=... level=INFO fiber=#0 message=message1 message=message2 cause="Error: Oh no!
// Error: Oh uh!"

Added in v2.0.0

logAnnotations

Retrieves the log annotations associated with the current scope.

Signature

export declare const logAnnotations: Effect<HashMap.HashMap<string, unknown>, never, never>

Added in v2.0.0

logDebug

Logs the specified messages at the DEBUG log level. DEBUG messages are not shown by default.

To view DEBUG messages, adjust the logging settings using Logger.withMinimumLogLevel and set the log level to LogLevel.Debug.

Signature

export declare const logDebug: (...message: ReadonlyArray<any>) => Effect<void, never, never>

Example

import { Effect, Logger, LogLevel } from "effect"

const program = Effect.logDebug("message1").pipe(Logger.withMinimumLogLevel(LogLevel.Debug))

// Effect.runFork(program)
// timestamp=... level=DEBUG fiber=#0 message=message1

Added in v2.0.0

logError

Logs the specified message or cause at the Error log level.

Signature

export declare const logError: (...message: ReadonlyArray<any>) => Effect<void, never, never>

Added in v2.0.0

logFatal

Logs the specified message or cause at the Fatal log level.

Signature

export declare const logFatal: (...message: ReadonlyArray<any>) => Effect<void, never, never>

Added in v2.0.0

logInfo

Logs the specified message or cause at the Info log level.

Signature

export declare const logInfo: (...message: ReadonlyArray<any>) => Effect<void, never, never>

Added in v2.0.0

logTrace

Logs the specified message or cause at the Trace log level.

Signature

export declare const logTrace: (...message: ReadonlyArray<any>) => Effect<void, never, never>

Added in v2.0.0

logWarning

Logs the specified message or cause at the Warning log level.

Signature

export declare const logWarning: (...message: ReadonlyArray<any>) => Effect<void, never, never>

Added in v2.0.0

logWithLevel

Logs the specified message or cause at the specified log level.

Signature

export declare const logWithLevel: (level: LogLevel, ...message: ReadonlyArray<any>) => Effect<void>

Added in v2.0.0

withLogSpan

Adds a log span to your effects, which tracks and logs the duration of operations or tasks. This is useful for performance monitoring and debugging time-sensitive processes.

Signature

export declare const withLogSpan: {
  (label: string): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(effect: Effect<A, E, R>, label: string): Effect<A, E, R>
}

Example

import { Effect } from "effect"

const program = Effect.gen(function* () {
  yield* Effect.sleep("1 second")
  yield* Effect.log("The job is finished!")
}).pipe(Effect.withLogSpan("myspan"))

// Effect.runFork(program)
// timestamp=... level=INFO fiber=#0 message="The job is finished!" myspan=1011ms

Added in v2.0.0

withUnhandledErrorLogLevel

Decides wether child fibers will report or not unhandled errors via the logger

Signature

export declare const withUnhandledErrorLogLevel: {
  (level: Option.Option<LogLevel>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(self: Effect<A, E, R>, level: Option.Option<LogLevel>): Effect<A, E, R>
}

Added in v2.0.0

mapping

as

This function maps the success value of an Effect value to a specified constant value.

Signature

export declare const as: {
  <B>(value: B): <A, E, R>(self: Effect<A, E, R>) => Effect<B, E, R>
  <A, E, R, B>(self: Effect<A, E, R>, value: B): Effect<B, E, R>
}

Added in v2.0.0

asSome

This function maps the success value of an Effect value to a Some value in an Option value. If the original Effect value fails, the returned Effect value will also fail.

Signature

export declare const asSome: <A, E, R>(self: Effect<A, E, R>) => Effect<Option.Option<A>, E, R>

Added in v2.0.0

asSomeError

This function maps the error value of an Effect value to a Some value in an Option value. If the original Effect value succeeds, the returned Effect value will also succeed.

Signature

export declare const asSomeError: <A, E, R>(self: Effect<A, E, R>) => Effect<A, Option.Option<E>, R>

Added in v2.0.0

asVoid

This function maps the success value of an Effect value to void. If the original Effect value succeeds, the returned Effect value will also succeed. If the original Effect value fails, the returned Effect value will fail with the same error.

Signature

export declare const asVoid: <A, E, R>(self: Effect<A, E, R>) => Effect<void, E, R>

Added in v2.0.0

flip

Returns an effect that swaps the error/success cases. This allows you to use all methods on the error channel, possibly before flipping back.

Signature

export declare const flip: <A, E, R>(self: Effect<A, E, R>) => Effect<E, A, R>

Added in v2.0.0

flipWith

Swaps the error/value parameters, applies the function f and flips the parameters back

Signature

export declare const flipWith: {
  <E, A, R, E2, A2, R2>(
    f: (effect: Effect<E, A, R>) => Effect<E2, A2, R2>
  ): (self: Effect<A, E, R>) => Effect<A2, E2, R2>
  <A, E, R, E2, A2, R2>(self: Effect<A, E, R>, f: (effect: Effect<E, A, R>) => Effect<E2, A2, R2>): Effect<A2, E2, R2>
}

Added in v2.0.0

map

Signature

export declare const map: {
  <A, B>(f: (a: A) => B): <E, R>(self: Effect<A, E, R>) => Effect<B, E, R>
  <A, E, R, B>(self: Effect<A, E, R>, f: (a: A) => B): Effect<B, E, R>
}

Added in v2.0.0

mapAccum

Statefully and effectfully maps over the elements of this chunk to produce new elements.

Signature

export declare const mapAccum: {
  <S, A, B, E, R>(
    zero: S,
    f: (s: S, a: A, i: number) => Effect<readonly [S, B], E, R>
  ): (elements: Iterable<A>) => Effect<[S, B[]], E, R>
  <A, S, B, E, R>(
    elements: Iterable<A>,
    zero: S,
    f: (s: S, a: A, i: number) => Effect<readonly [S, B], E, R>
  ): Effect<[S, B[]], E, R>
}

Added in v2.0.0

mapBoth

Returns an effect whose failure and success channels have been mapped by the specified onFailure and onSuccess functions.

Signature

export declare const mapBoth: {
  <E, E2, A, A2>(options: {
    readonly onFailure: (e: E) => E2
    readonly onSuccess: (a: A) => A2
  }): <R>(self: Effect<A, E, R>) => Effect<A2, E2, R>
  <A, E, R, E2, A2>(
    self: Effect<A, E, R>,
    options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 }
  ): Effect<A2, E2, R>
}

Added in v2.0.0

mapError

Returns an effect with its error channel mapped using the specified function.

Signature

export declare const mapError: {
  <E, E2>(f: (e: E) => E2): <A, R>(self: Effect<A, E, R>) => Effect<A, E2, R>
  <A, E, R, E2>(self: Effect<A, E, R>, f: (e: E) => E2): Effect<A, E2, R>
}

Added in v2.0.0

mapErrorCause

Returns an effect with its full cause of failure mapped using the specified function. This can be used to transform errors while preserving the original structure of Cause.

See sandbox, catchAllCause for other functions for dealing with defects.

Signature

export declare const mapErrorCause: {
  <E, E2>(f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): <A, R>(self: Effect<A, E, R>) => Effect<A, E2, R>
  <A, E, R, E2>(self: Effect<A, E, R>, f: (cause: Cause.Cause<E>) => Cause.Cause<E2>): Effect<A, E2, R>
}

Added in v2.0.0

merge

Returns a new effect where the error channel has been merged into the success channel to their common combined type.

Signature

export declare const merge: <A, E, R>(self: Effect<A, E, R>) => Effect<A | E, never, R>

Added in v2.0.0

negate

Returns a new effect where boolean value of this effect is negated.

Signature

export declare const negate: <E, R>(self: Effect<boolean, E, R>) => Effect<boolean, E, R>

Added in v2.0.0

metrics

labelMetrics

Tags each metric in this effect with the specific tag.

Signature

export declare const labelMetrics: {
  (labels: Iterable<MetricLabel.MetricLabel>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(self: Effect<A, E, R>, labels: Iterable<MetricLabel.MetricLabel>): Effect<A, E, R>
}

Added in v2.0.0

labelMetricsScoped

Tags each metric in a scope with a the specific tag.

Signature

export declare const labelMetricsScoped: (
  labels: ReadonlyArray<MetricLabel.MetricLabel>
) => Effect<void, never, Scope.Scope>

Added in v2.0.0

metricLabels

Retrieves the metric labels associated with the current scope.

Signature

export declare const metricLabels: Effect<readonly MetricLabel.MetricLabel[], never, never>

Added in v2.0.0

tagMetrics

Tags each metric in this effect with the specific tag.

Signature

export declare const tagMetrics: {
  (key: string, value: string): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>
  (values: Record<string, string>): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(effect: Effect<A, E, R>, key: string, value: string): Effect<A, E, R>
  <A, E, R>(effect: Effect<A, E, R>, values: Record<string, string>): Effect<A, E, R>
}

Added in v2.0.0

tagMetricsScoped

Tags each metric in a scope with a the specific tag.

Signature

export declare const tagMetricsScoped: (key: string, value: string) => Effect<void, never, Scope.Scope>

Added in v2.0.0

withMetric

Signature

export declare const withMetric: {
  <Type, In, Out>(metric: Metric.Metric<Type, In, Out>): <A extends In, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A extends In, E, R, Type, In, Out>(self: Effect<A, E, R>, metric: Metric.Metric<Type, In, Out>): Effect<A, E, R>
}

Added in v2.0.0

models

Adapter (interface)

Signature

export interface Adapter {
  <A, E, R>(self: Effect<A, E, R>): Effect<A, E, R>
  <A, _A, _E, _R>(a: A, ab: (a: A) => Effect<_A, _E, _R>): Effect<_A, _E, _R>
  <A, B, _A, _E, _R>(a: A, ab: (a: A) => B, bc: (b: B) => Effect<_A, _E, _R>): Effect<_A, _E, _R>
  <A, B, C, _A, _E, _R>(a: A, ab: (a: A) => B, bc: (b: B) => C, cd: (c: C) => Effect<_A, _E, _R>): Effect<_A, _E, _R>
  <A, B, C, D, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (g: H) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, L, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => L,
    lm: (l: L) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, L, M, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => L,
    lm: (l: L) => M,
    mn: (m: M) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => L,
    lm: (l: L) => M,
    mn: (m: M) => N,
    no: (n: N) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => L,
    lm: (l: L) => M,
    mn: (m: M) => N,
    no: (n: N) => O,
    op: (o: O) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => L,
    lm: (l: L) => M,
    mn: (m: M) => N,
    no: (n: N) => O,
    op: (o: O) => P,
    pq: (p: P) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => L,
    lm: (l: L) => M,
    mn: (m: M) => N,
    no: (n: N) => O,
    op: (o: O) => P,
    pq: (p: P) => Q,
    qr: (q: Q) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => L,
    lm: (l: L) => M,
    mn: (m: M) => N,
    no: (n: N) => O,
    op: (o: O) => P,
    pq: (p: P) => Q,
    qr: (q: Q) => R,
    rs: (r: R) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => L,
    lm: (l: L) => M,
    mn: (m: M) => N,
    no: (n: N) => O,
    op: (o: O) => P,
    pq: (p: P) => Q,
    qr: (q: Q) => R,
    rs: (r: R) => S,
    st: (s: S) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
  <A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, _A, _E, _R>(
    a: A,
    ab: (a: A) => B,
    bc: (b: B) => C,
    cd: (c: C) => D,
    de: (d: D) => E,
    ef: (e: E) => F,
    fg: (f: F) => G,
    gh: (g: G) => H,
    hi: (h: H) => I,
    ij: (i: I) => J,
    jk: (j: J) => K,
    kl: (k: K) => L,
    lm: (l: L) => M,
    mn: (m: M) => N,
    no: (n: N) => O,
    op: (o: O) => P,
    pq: (p: P) => Q,
    qr: (q: Q) => R,
    rs: (r: R) => S,
    st: (s: S) => T,
    tu: (s: T) => Effect<_A, _E, _R>
  ): Effect<_A, _E, _R>
}

Added in v2.0.0

Blocked (interface)

Signature

export interface Blocked<out A, out E> extends Effect<A, E> {
  readonly _op: "Blocked"
  readonly effect_instruction_i0: RequestBlock
  readonly effect_instruction_i1: Effect<A, E>
}

Added in v2.0.0

Effect (interface)

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.

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.

Signature

export interface Effect<out A, out E = never, out R = never> extends Effect.Variance<A, E, R>, Pipeable {
  readonly [Unify.typeSymbol]?: unknown
  readonly [Unify.unifySymbol]?: EffectUnify<this>
  readonly [Unify.ignoreSymbol]?: EffectUnifyIgnore
  [Symbol.iterator](): EffectGenerator<Effect<A, E, R>>
}

Added in v2.0.0

EffectGenerator (interface)

Signature

export interface EffectGenerator<T extends Effect<any, any, any>> {
  next(...args: ReadonlyArray<any>): IteratorResult<YieldWrap<T>, Effect.Success<T>>
}

Added in v3.0.0

EffectUnify (interface)

Signature

export interface EffectUnify<A extends { [Unify.typeSymbol]?: any }>
  extends Either.EitherUnify<A>,
    Option.OptionUnify<A>,
    Context.TagUnify<A> {
  Effect?: () => A[Unify.typeSymbol] extends Effect<infer A0, infer E0, infer R0> | infer _ ? Effect<A0, E0, R0> : never
}

Added in v2.0.0

EffectUnifyIgnore (interface)

Signature

export interface EffectUnifyIgnore {
  Tag?: true
  Option?: true
  Either?: true
}

Added in v2.0.0

FunctionWithSpanOptions (interface)

Wraps a function that returns an effect with a new span for tracing.

Signature

export interface FunctionWithSpanOptions {
  readonly name: string
  readonly attributes?: Record<string, unknown> | undefined
  readonly links?: ReadonlyArray<Tracer.SpanLink> | undefined
  readonly parent?: Tracer.AnySpan | undefined
  readonly root?: boolean | undefined
  readonly context?: Context.Context<never> | undefined
  readonly kind?: Tracer.SpanKind | undefined
}

Added in v3.2.0

Tag (namespace)

Added in v2.0.0

ProhibitedType (interface)

Signature

export interface ProhibitedType {
  _op?: "propety name _op is forbidden"
  _tag?: "propety name _tag is forbidden"
  of?: "propety name of is forbidden"
  context?: "propety name context is forbidden"
  key?: "propety name key is forbidden"
  stack?: "propety name stack is forbidden"
}

Added in v2.0.0

AllowedType (type alias)

Signature

export type AllowedType = (Record<PropertyKey, any> & ProhibitedType) | string | number | symbol

Added in v2.0.0

optionality

fromNullable

Returns an effect that errors with NoSuchElementException if the value is null or undefined, otherwise succeeds with the value.

Signature

export declare const fromNullable: <A>(value: A) => Effect<NonNullable<A>, Cause.NoSuchElementException, never>

Added in v2.0.0

optionFromOptional

Wraps the success value of this effect with Option.some, and maps Cause.NoSuchElementException to Option.none.

Signature

export declare const optionFromOptional: <A, E, R>(
  self: Effect<A, E, R>
) => Effect<Option.Option<A>, Exclude<E, Cause.NoSuchElementException>, R>

Added in v2.0.0

random

random

Retreives the Random service from the context.

Signature

export declare const random: Effect<Random.Random, never, never>

Added in v2.0.0

randomWith

Retreives the Random service from the context and uses it to run the specified workflow.

Signature

export declare const randomWith: <A, E, R>(f: (random: Random.Random) => Effect<A, E, R>) => Effect<A, E, R>

Added in v2.0.0

withRandom

Executes the specified workflow with the specified implementation of the random service.

Signature

export declare const withRandom: {
  <X extends Random.Random>(value: X): <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, R>
  <X extends Random.Random, A, E, R>(effect: Effect<A, E, R>, value: X): Effect<A, E, R>
}

Added in v2.0.0

refinements

isEffect

This function returns true if the specified value is an Effect value, false otherwise.

This function can be useful for checking the type of a value before attempting to operate on it as an Effect value. For example, you could use isEffect to check the type of a value before using it as an argument to a function that expects an Effect value.

Signature

export declare const isEffect: (u: unknown) => u is Effect<unknown, unknown, unknown>

Added in v2.0.0

repetition / recursion

Repeat (namespace)

Added in v2.0.0

Options (interface)

Signature

export interface Options<A> {
  while?: ((_: A) => boolean | Effect<boolean, any, any>) | undefined
  until?: ((_: A) => boolean | Effect<boolean, any, any>) | undefined
  times?: number | undefined
  schedule?: Schedule.Schedule<any, A, any> | undefined
}

Added in v2.0.0

Return (type alias)

Signature

export type Return<R, E, A, O extends Options<A>> =
  Effect<
    O extends { schedule: Schedule.Schedule<infer Out, infer _I, infer _R> }
      ? Out
      : O extends { until: Refinement<A, infer B> }
        ? B
        : A,
    | E
    | (O extends { while: (...args: Array<any>) => Effect<infer _A, infer E, infer _R> } ? E : never)
    | (O extends { until: (...args: Array<any>) => Effect<infer _A, infer E, infer _R> } ? E : never),
    | R
    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer R> } ? R : never)
    | (O extends { while: (...args: Array<any>) => Effect<infer _A, infer _E, infer R> } ? R : never)
    | (O extends { until: (...args: Array<any>) => Effect<infer _A, infer _E, infer R> } ? R : never)
  > extends infer Z
    ? Z
    : never

Added in v2.0.0

forever

Repeats this effect forever (until the first error).

Signature

export declare const forever: <A, E, R>(self: Effect<A, E, R>) => Effect<never, E, R>

Added in v2.0.0

iterate

The Effect.iterate function allows you to iterate with an effectful operation. It uses an effectful body operation to change the state during each iteration and continues the iteration as long as the while function evaluates to true:

Effect.iterate(initial, options: { while, body })

We can think of Effect.iterate as equivalent to a while loop in JavaScript:

let result = initial

while (options.while(result)) {
  result = options.body(result)
}

return result

Signature

export declare const iterate: {
  <A, B extends A, R, E>(
    initial: A,
    options: { readonly while: Refinement<A, B>; readonly body: (b: B) => Effect<A, E, R> }
  ): Effect<A, E, R>
  <A, R, E>(
    initial: A,
    options: { readonly while: Predicate<A>; readonly body: (a: A) => Effect<A, E, R> }
  ): Effect<A, E, R>
}

Added in v2.0.0

loop

The Effect.loop function allows you to repeatedly change the state based on an step function until a condition given by the while function is evaluated to true:

Effect.loop(initial, options: { while, step, body })

It collects all intermediate states in an array and returns it as the final result.

We can think of Effect.loop as equivalent to a while loop in JavaScript:

let state = initial
const result = []

while (options.while(state)) {
  result.push(options.body(state))
  state = options.step(state)
}

return result

Signature

export declare const loop: {
  <A, B extends A, C, E, R>(
    initial: A,
    options: {
      readonly while: Refinement<A, B>
      readonly step: (b: B) => A
      readonly body: (b: B) => Effect<C, E, R>
      readonly discard?: false | undefined
    }
  ): Effect<C[], E, R>
  <A, C, E, R>(
    initial: A,
    options: {
      readonly while: (a: A) => boolean
      readonly step: (a: A) => A
      readonly body: (a: A) => Effect<C, E, R>
      readonly discard?: false | undefined
    }
  ): Effect<C[], E, R>
  <A, B extends A, C, E, R>(
    initial: A,
    options: {
      readonly while: Refinement<A, B>
      readonly step: (b: B) => A
      readonly body: (b: B) => Effect<C, E, R>
      readonly discard: true
    }
  ): Effect<void, E, R>
  <A, C, E, R>(
    initial: A,
    options: {
      readonly while: (a: A) => boolean
      readonly step: (a: A) => A
      readonly body: (a: A) => Effect<C, E, R>
      readonly discard: true
    }
  ): Effect<void, E, R>
}

Added in v2.0.0

repeat

The repeat function returns a new effect that repeats the given effect according to a specified schedule or until the first failure. The scheduled recurrences are in addition to the initial execution, so Effect.repeat(action, Schedule.once) executes action once initially, and if it succeeds, repeats it an additional time.

Signature

export declare const repeat: {
  <O extends Repeat.Options<A>, A>(
    options: O
  ): <E, R>(
    self: Effect<A, E, R>
  ) => Effect<
    O extends { schedule: Schedule.Schedule<infer Out, infer _I, infer _R> }
      ? Out
      : O extends { until: Refinement<A, infer B extends A> }
        ? B
        : A,
    | E
    | (O extends { while: (...args: any[]) => Effect<infer _A, infer E, infer _R> } ? E : never)
    | (O extends { until: (...args: any[]) => Effect<infer _A, infer E, infer _R> } ? E : never),
    | R
    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer R> } ? R : never)
    | (O extends { while: (...args: any[]) => Effect<infer _A, infer _E, infer R> } ? R : never)
    | (O extends { until: (...args: any[]) => Effect<infer _A, infer _E, infer R> } ? R : never)
  >
  <B, A, R1>(schedule: Schedule.Schedule<B, A, R1>): <E, R>(self: Effect<A, E, R>) => Effect<B, E, R1 | R>
  <A, E, R, O extends Repeat.Options<A>>(
    self: Effect<A, E, R>,
    options: O
  ): Effect<
    O extends { schedule: Schedule.Schedule<infer Out, infer _I, infer _R> }
      ? Out
      : O extends { until: Refinement<A, infer B extends A> }
        ? B
        : A,
    | E
    | (O extends { while: (...args: any[]) => Effect<infer _A, infer E, infer _R> } ? E : never)
    | (O extends { until: (...args: any[]) => Effect<infer _A, infer E, infer _R> } ? E : never),
    | R
    | (O extends { schedule: Schedule.Schedule<infer _O, infer _I, infer R> } ? R : never)
    | (O extends { while: (...args: any[]) => Effect<infer _A, infer _E, infer R> } ? R : never)
    | (O extends { until: (...args: any[]) => Effect<infer _A, infer _E, infer R> } ? R : never)
  >
  <A, E, R, B, R1>(self: Effect<A, E, R>, schedule: Schedule.Schedule<B, A, R1>): Effect<B, E, R | R1>
}

Example

// Success Example
import { Effect, Schedule, Console } from "effect"

const action = Console.log("success")
const policy = Schedule.addDelay(Schedule.recurs(2), () => "100 millis")
const program = Effect.repeat(action, policy)

Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`))

Example

// Failure Example
import { Effect, Schedule } from "effect"

let count = 0

// Define an async effect that simulates an action with possible failures
const action = Effect.async<string, string>((resume) => {
  if (count > 1) {
    console.log("failure")
    resume(Effect.fail("Uh oh!"))
  } else {
    count++
    console.log("success")
    resume(Effect.succeed("yay!"))
  }
})

const policy = Schedule.addDelay(Schedule.recurs(2), () => "100 millis")
const program = Effect.repeat(action, policy)

Effect.runPromiseExit(program).then(console.log)

Added in v2.0.0

repeatN

The repeatN function returns a new effect that repeats the specified effect a given number of times or until the first failure. The repeats are in addition to the initial execution, so Effect.repeatN(action, 1) executes action once initially and then repeats it one additional time if it succeeds.

Signature

export declare const repeatN: {
  (n: number): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(self: Effect<A, E, R>, n: number): Effect<A, E, R>
}

Example

import { Effect, Console } from "effect"

const action = Console.log("success")
const program = Effect.repeatN(action, 2)

Effect.runPromise(program)

Added in v2.0.0

repeatOrElse

The repeatOrElse function returns a new effect that repeats the specified effect according to the given schedule or until the first failure. When a failure occurs, the failure value and schedule output are passed to a specified handler. Scheduled recurrences are in addition to the initial execution, so Effect.repeat(action, Schedule.once) executes action once initially and then repeats it an additional time if it succeeds.

Signature

export declare const repeatOrElse: {
  <R2, A, B, E, E2, R3>(
    schedule: Schedule.Schedule<B, A, R2>,
    orElse: (error: E, option: Option.Option<B>) => Effect<B, E2, R3>
  ): <R>(self: Effect<A, E, R>) => Effect<B, E2, R2 | R3 | R>
  <A, E, R, R2, B, E2, R3>(
    self: Effect<A, E, R>,
    schedule: Schedule.Schedule<B, A, R2>,
    orElse: (error: E, option: Option.Option<B>) => Effect<B, E2, R3>
  ): Effect<B, E2, R | R2 | R3>
}

Example

import { Effect, Schedule } from "effect"

let count = 0

// Define an async effect that simulates an action with possible failures
const action = Effect.async<string, string>((resume) => {
  if (count > 1) {
    console.log("failure")
    resume(Effect.fail("Uh oh!"))
  } else {
    count++
    console.log("success")
    resume(Effect.succeed("yay!"))
  }
})

const policy = Schedule.addDelay(
  Schedule.recurs(2), // Repeat for a maximum of 2 times
  () => "100 millis" // Add a delay of 100 milliseconds between repetitions
)

const program = Effect.repeatOrElse(action, policy, () =>
  Effect.sync(() => {
    console.log("orElse")
    return count - 1
  })
)

Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`))

Added in v2.0.0

schedule

Runs this effect according to the specified schedule.

See scheduleFrom for a variant that allows the schedule’s decision to depend on the result of this effect.

Signature

export declare const schedule: {
  <R2, Out>(schedule: Schedule.Schedule<Out, unknown, R2>): <A, E, R>(self: Effect<A, E, R>) => Effect<Out, E, R2 | R>
  <A, E, R, R2, Out>(self: Effect<A, E, R>, schedule: Schedule.Schedule<Out, unknown, R2>): Effect<Out, E, R | R2>
}

Added in v2.0.0

scheduleForked

Runs this effect according to the specified schedule in a new fiber attached to the current scope.

Signature

export declare const scheduleForked: {
  <Out, R2>(
    schedule: Schedule.Schedule<Out, unknown, R2>
  ): <A, E, R>(self: Effect<A, E, R>) => Effect<Fiber.RuntimeFiber<Out, E>, never, Scope.Scope | R2 | R>
  <A, E, R, Out, R2>(
    self: Effect<A, E, R>,
    schedule: Schedule.Schedule<Out, unknown, R2>
  ): Effect<Fiber.RuntimeFiber<Out, E>, never, Scope.Scope | R | R2>
}

Added in v2.0.0

scheduleFrom

Runs this effect according to the specified schedule starting from the specified input value.

Signature

export declare const scheduleFrom: {
  <R2, In, Out>(
    initial: In,
    schedule: Schedule.Schedule<Out, In, R2>
  ): <E, R>(self: Effect<In, E, R>) => Effect<Out, E, R2 | R>
  <In, E, R, R2, Out>(
    self: Effect<In, E, R>,
    initial: In,
    schedule: Schedule.Schedule<Out, In, R2>
  ): Effect<Out, E, R | R2>
}

Added in v2.0.0

whileLoop

Signature

export declare const whileLoop: <A, E, R>(options: {
  readonly while: LazyArg<boolean>
  readonly body: LazyArg<Effect<A, E, R>>
  readonly step: (a: A) => void
}) => Effect<void, E, R>

Added in v2.0.0

requests & batching

blocked

Signature

export declare const blocked: <A, E>(blockedRequests: RequestBlock, _continue: Effect<A, E, never>) => Blocked<A, E>

Added in v2.0.0

cacheRequestResult

Signature

export declare const cacheRequestResult: <A extends Request.Request<any, any>>(
  request: A,
  result: Request.Request.Result<A>
) => Effect<void>

Added in v2.0.0

request

Signature

export declare const request: {
  <
    A extends Request.Request<any, any>,
    Ds extends RequestResolver<A, never> | Effect<RequestResolver<A, never>, any, any>
  >(
    dataSource: Ds
  ): (
    self: A
  ) => Effect<
    Request.Request.Success<A>,
    Request.Request.Error<A>,
    [Ds] extends [Effect<any, any, any>] ? Effect.Context<Ds> : never
  >
  <
    Ds extends RequestResolver<A, never> | Effect<RequestResolver<A, never>, any, any>,
    A extends Request.Request<any, any>
  >(
    self: A,
    dataSource: Ds
  ): Effect<
    Request.Request.Success<A>,
    Request.Request.Error<A>,
    [Ds] extends [Effect<any, any, any>] ? Effect.Context<Ds> : never
  >
}

Added in v2.0.0

runRequestBlock

Signature

export declare const runRequestBlock: (blockedRequests: RequestBlock) => Effect<void>

Added in v2.0.0

step

Signature

export declare const step: <A, E, R>(self: Effect<A, E, R>) => Effect<Exit.Exit<A, E> | Blocked<A, E>, never, R>

Added in v2.0.0

withRequestBatching

Signature

export declare const withRequestBatching: {
  (requestBatching: boolean): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(self: Effect<A, E, R>, requestBatching: boolean): Effect<A, E, R>
}

Added in v2.0.0

withRequestCache

Signature

export declare const withRequestCache: {
  (cache: Request.Cache): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(self: Effect<A, E, R>, cache: Request.Cache): Effect<A, E, R>
}

Added in v2.0.0

withRequestCaching

Signature

export declare const withRequestCaching: {
  (strategy: boolean): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(self: Effect<A, E, R>, strategy: boolean): Effect<A, E, R>
}

Added in v2.0.0

runtime

getRuntimeFlags

Retrieves an effect that succeeds with the current runtime flags, which govern behavior and features of the runtime system.

Signature

export declare const getRuntimeFlags: Effect<RuntimeFlags.RuntimeFlags, never, never>

Added in v2.0.0

patchRuntimeFlags

Signature

export declare const patchRuntimeFlags: (patch: RuntimeFlagsPatch.RuntimeFlagsPatch) => Effect<void>

Added in v2.0.0

runtime

Returns an effect that accesses the runtime, which can be used to (unsafely) execute tasks. This is useful for integration with legacy code that must call back into Effect code.

Signature

export declare const runtime: <R = never>() => Effect<Runtime.Runtime<R>, never, R>

Added in v2.0.0

withRuntimeFlagsPatch

Signature

export declare const withRuntimeFlagsPatch: {
  (update: RuntimeFlagsPatch.RuntimeFlagsPatch): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(self: Effect<A, E, R>, update: RuntimeFlagsPatch.RuntimeFlagsPatch): Effect<A, E, R>
}

Added in v2.0.0

withRuntimeFlagsPatchScoped

Signature

export declare const withRuntimeFlagsPatchScoped: (
  update: RuntimeFlagsPatch.RuntimeFlagsPatch
) => Effect<void, never, Scope.Scope>

Added in v2.0.0

scheduler

withScheduler

Sets the provided scheduler for usage in the wrapped effect

Signature

export declare const withScheduler: {
  (scheduler: Scheduler.Scheduler): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  <A, E, R>(self: Effect<A, E, R>, scheduler: Scheduler.Scheduler): Effect<A, E, R>
}

Added in v2.0.0

scoping, resources & finalization

acquireRelease

This function constructs a scoped resource from an acquire and release Effect value.

If the acquire Effect value successfully completes execution, then the release Effect value will be added to the finalizers associated with the scope of this Effect value, and it is guaranteed to be run when the scope is closed.

The acquire and release Effect values will be run uninterruptibly. Additionally, the release Effect value may depend on the Exit value specified when the scope is closed.

Signature

export declare const acquireRelease: {
  <A, X, R2>(
    release: (a: A, exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R2>
  ): <E, R>(acquire: Effect<A, E, R>) => Effect<A, E, Scope.Scope | R2 | R>
  <A, E, R, X, R2>(
    acquire: Effect<A, E, R>,
    release: (a: A, exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R2>
  ): Effect<A, E, Scope.Scope | R | R2>
}

Added in v2.0.0

acquireReleaseInterruptible

This function constructs a scoped resource from an acquire and release Effect value.

If the acquire Effect value successfully completes execution, then the release Effect value will be added to the finalizers associated with the scope of this Effect value, and it is guaranteed to be run when the scope is closed.

The acquire Effect values will be run interruptibly. The release Effect values will be run uninterruptibly.

Additionally, the release Effect value may depend on the Exit value specified when the scope is closed.

Signature

export declare const acquireReleaseInterruptible: {
  <X, R2>(
    release: (exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R2>
  ): <A, E, R>(acquire: Effect<A, E, R>) => Effect<A, E, Scope.Scope | R2 | R>
  <A, E, R, X, R2>(
    acquire: Effect<A, E, R>,
    release: (exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R2>
  ): Effect<A, E, Scope.Scope | R | R2>
}

Added in v2.0.0

acquireUseRelease

This function is used to ensure that an Effect value that represents the acquisition of a resource (for example, opening a file, launching a thread, etc.) will not be interrupted, and that the resource will always be released when the Effect value completes execution.

acquireUseRelease does the following:

  1. Ensures that the Effect value that acquires the resource will not be interrupted. Note that acquisition may still fail due to internal reasons (such as an uncaught exception).
  2. Ensures that the release Effect value will not be interrupted, and will be executed as long as the acquisition Effect value successfully acquires the resource.

During the time period between the acquisition and release of the resource, the use Effect value will be executed.

If the release Effect value fails, then the entire Effect value will fail, even if the use Effect value succeeds. If this fail-fast behavior is not desired, errors produced by the release Effect value can be caught and ignored.

Signature

export declare const acquireUseRelease: {
  <A2, E2, R2, A, X, R3>(
    use: (a: A) => Effect<A2, E2, R2>,
    release: (a: A, exit: Exit.Exit<A2, E2>) => Effect<X, never, R3>
  ): <E, R>(acquire: Effect<A, E, R>) => Effect<A2, E2 | E, R2 | R3 | R>
  <A, E, R, A2, E2, R2, X, R3>(
    acquire: Effect<A, E, R>,
    use: (a: A) => Effect<A2, E2, R2>,
    release: (a: A, exit: Exit.Exit<A2, E2>) => Effect<X, never, R3>
  ): Effect<A2, E | E2, R | R2 | R3>
}

Added in v2.0.0

addFinalizer

This function adds a finalizer to the scope of the calling Effect value. The finalizer is guaranteed to be run when the scope is closed, and it may depend on the Exit value that the scope is closed with.

Signature

export declare const addFinalizer: <X, R>(
  finalizer: (exit: Exit.Exit<unknown, unknown>) => Effect<X, never, R>
) => Effect<void, never, Scope.Scope | R>

Added in v2.0.0

ensuring

Returns an effect that, if this effect starts execution, then the specified finalizer is guaranteed to be executed, whether this effect succeeds, fails, or is interrupted.

For use cases that need access to the effect’s result, see onExit.

Finalizers offer very powerful guarantees, but they are low-level, and should generally not be used for releasing resources. For higher-level logic built on ensuring, see the acquireRelease family of methods.

Signature

export declare const ensuring: {
  <X, R1>(finalizer: Effect<X, never, R1>): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R1 | R>
  <A, E, R, X, R1>(self: Effect<A, E, R>, finalizer: Effect<X, never, R1>): Effect<A, E, R | R1>
}

Added in v2.0.0

finalizersMask

Signature

export declare const finalizersMask: (
  strategy: ExecutionStrategy
) => <A, E, R>(
  self: (restore: <A1, E1, R1>(self: Effect<A1, E1, R1>) => Effect<A1, E1, R1>) => Effect<A, E, R>
) => Effect<A, E, R>

Added in v2.0.0

onError

Runs the specified effect if this effect fails, providing the error to the effect if it exists. The provided effect will not be interrupted.

Signature

export declare const onError: {
  <E, X, R2>(
    cleanup: (cause: Cause.Cause<E>) => Effect<X, never, R2>
  ): <A, R>(self: Effect<A, E, R>) => Effect<A, E, R2 | R>
  <A, E, R, X, R2>(
    self: Effect<A, E, R>,
    cleanup: (cause: Cause.Cause<E>) => Effect<X, never, R2>
  ): Effect<A, E, R | R2>
}

Added in v2.0.0

onExit

Ensures that a cleanup functions runs, whether this effect succeeds, fails, or is interrupted.

Signature

export declare const onExit: {
  <A, E, X, R2>(
    cleanup: (exit: Exit.Exit<A, E>) => Effect<X, never, R2>
  ): <R>(self: Effect<A, E, R>) => Effect<A, E, R2 | R>
  <A, E, R, X, R2>(
    self: Effect<A, E, R>,
    cleanup: (exit: Exit.Exit<A, E>) => Effect<X, never, R2>
  ): Effect<A, E, R | R2>
}

Added in v2.0.0

parallelFinalizers

Signature

export declare const parallelFinalizers: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>

Added in v2.0.0

scope

Signature

export declare const scope: Effect<Scope.Scope, never, Scope.Scope>

Added in v2.0.0

scopeWith

Accesses the current scope and uses it to perform the specified effect.

Signature

export declare const scopeWith: <A, E, R>(f: (scope: Scope.Scope) => Effect<A, E, R>) => Effect<A, E, Scope.Scope | R>

Added in v2.0.0

scoped

Scopes all resources used in this workflow to the lifetime of the workflow, ensuring that their finalizers are run as soon as this workflow completes execution, whether by success, failure, or interruption.

Signature

export declare const scoped: <A, E, R>(effect: Effect<A, E, R>) => Effect<A, E, Exclude<R, Scope.Scope>>

Added in v2.0.0

sequentialFinalizers

Returns a new scoped workflow that runs finalizers added to the scope of this workflow sequentially in the reverse of the order in which they were added. Note that finalizers are run sequentially by default so this only has meaning if used within a scope where finalizers are being run in parallel.

Signature

export declare const sequentialFinalizers: <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>

Added in v2.0.0

using

Scopes all resources acquired by resource to the lifetime of use without effecting the scope of any resources acquired by use.

Signature

export declare const using: {
  <A, A2, E2, R2>(
    use: (a: A) => Effect<A2, E2, R2>
  ): <E, R>(self: Effect<A, E, R>) => Effect<A2, E2 | E, R2 | Exclude<R, Scope.Scope>>
  <A, E, R, A2, E2, R2>(
    self: Effect<A, E, R>,
    use: (a: A) => Effect<A2, E2, R2>
  ): Effect<A2, E | E2, R2 | Exclude<R, Scope.Scope>>
}

Added in v2.0.0

withEarlyRelease

Returns a new scoped workflow that returns the result of this workflow as well as a finalizer that can be run to close the scope of this workflow.

Signature

export declare const withEarlyRelease: <A, E, R>(
  self: Effect<A, E, R>
) => Effect<[Effect<void, never, never>, A], E, Scope.Scope | R>

Added in v2.0.0

semaphore

Permit (interface)

Signature

export interface Permit {
  readonly index: number
}

Added in v2.0.0

Semaphore (interface)

Signature

export interface Semaphore {
  /** when the given amount of permits are available, run the effect and release the permits when finished */
  withPermits(permits: number): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R>
  /** take the given amount of permits, suspending if they are not yet available */
  take(permits: number): Effect<number>
  /** release the given amount of permits, and return the resulting available permits */
  release(permits: number): Effect<number>
  /** release all the taken permits, and return the resulting available permits */
  releaseAll: Effect<number>
}

Added in v2.0.0

makeSemaphore

Creates a new Semaphore

Signature

export declare const makeSemaphore: (permits: number) => Effect<Semaphore>

Added in v2.0.0

unsafeMakeSemaphore

Unsafely creates a new Semaphore

Signature

export declare const unsafeMakeSemaphore: (permits: number) => Semaphore

Added in v2.0.0

sequencing

andThen

Executes a sequence of two actions, typically two Effects, where the second action can depend on the result of the first action.

The that action can take various forms:

  • a value
  • a function returning a value
  • a promise
  • a function returning a promise
  • an effect
  • a function returning an effect

Signature

export declare const andThen: {
  <A, X>(
    f: (a: NoInfer<A>) => X
  ): <E, R>(
    self: Effect<A, E, R>
  ) => [X] extends [Effect<infer A1, infer E1, infer R1>]
    ? Effect<A1, E | E1, R | R1>
    : [X] extends [PromiseLike<infer A1>]
      ? Effect<A1, Cause.UnknownException | E, R>
      : Effect<X, E, R>
  <X>(
    f: NotFunction<X>
  ): <A, E, R>(
    self: Effect<A, E, R>
  ) => [X] extends [Effect<infer A1, infer E1, infer R1>]
    ? Effect<A1, E | E1, R | R1>
    : [X] extends [PromiseLike<infer A1>]
      ? Effect<A1, Cause.UnknownException | E, R>
      : Effect<X, E, R>
  <A, E, R, X>(
    self: Effect<A, E, R>,
    f: (a: NoInfer<A>) => X
  ): [X] extends [Effect<infer A1, infer E1, infer R1>]
    ? Effect<A1, E | E1, R | R1>
    : [X] extends [PromiseLike<infer A1>]
      ? Effect<A1, Cause.UnknownException | E, R>
      : Effect<X, E, R>
  <A, E, R, X>(
    self: Effect<A, E, R>,
    f: NotFunction<X>
  ): [X] extends [Effect<infer A1, infer E1, infer R1>]
    ? Effect<A1, E | E1, R | R1>
    : [X] extends [PromiseLike<infer A1>]
      ? Effect<A1, Cause.UnknownException | E, R>
      : Effect<X, E, R>
}

Example

import { Effect } from "effect"

assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen(1))), 1)
assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen((s) => s.length))), 2)

assert.deepStrictEqual(await Effect.runPromise(Effect.succeed("aa").pipe(Effect.andThen(Promise.resolve(1)))), 1)
assert.deepStrictEqual(
  await Effect.runPromise(Effect.succeed("aa").pipe(Effect.andThen((s) => Promise.resolve(s.length)))),
  2
)

assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen(Effect.succeed(1)))), 1)
assert.deepStrictEqual(Effect.runSync(Effect.succeed("aa").pipe(Effect.andThen((s) => Effect.succeed(s.length)))), 2)

Added in v2.0.0

flatMap

This function is a pipeable operator that maps over an Effect value, flattening the result of the mapping function into a new Effect value.

Signature

export declare const flatMap: {
  <A, B, E1, R1>(f: (a: A) => Effect<B, E1, R1>): <E, R>(self: Effect<A, E, R>) => Effect<B, E1 | E, R1 | R>
  <A, E, R, B, E1, R1>(self: Effect<A, E, R>, f: (a: A) => Effect<B, E1, R1>): Effect<B, E | E1, R | R1>
}

Added in v2.0.0

flatten

Signature

export declare const flatten: <A, E1, R1, E, R>(self: Effect<Effect<A, E1, R1>, E, R>) => Effect<A, E1 | E, R1 | R>

Added in v2.0.0

race

Returns an effect that races this effect with the specified effect, returning the first successful A from the faster side. If one effect succeeds, the other will be interrupted. If neither succeeds, then the effect will fail with some error.

Signature

export declare const race: {
  <A2, E2, R2>(that: Effect<A2, E2, R2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | E, R2 | R>
  <A, E, R, A2, E2, R2>(self: Effect<A, E, R>, that: Effect<A2, E2, R2>): Effect<A | A2, E | E2, R | R2>
}

Added in v2.0.0

raceAll

Returns an effect that races this effect with all the specified effects, yielding the value of the first effect to succeed with a value. Losers of the race will be interrupted immediately

Signature

export declare const raceAll: <Eff extends Effect<any, any, any>>(
  all: Iterable<Eff>
) => Effect<Effect.Success<Eff>, Effect.Error<Eff>, Effect.Context<Eff>>

Added in v2.0.0

raceFirst

Returns an effect that races this effect with the specified effect, yielding the first result to complete, whether by success or failure. If neither effect completes, then the composed effect will not complete.

WARNING: The raced effect will safely interrupt the “loser”, but will not resume until the loser has been cleanly terminated. If early return is desired, then instead of performing l raceFirst r, perform l.disconnect raceFirst r.disconnect, which disconnects left and right interrupt signal, allowing a fast return, with interruption performed in the background.

Signature

export declare const raceFirst: {
  <A2, E2, R2>(that: Effect<A2, E2, R2>): <A, E, R>(self: Effect<A, E, R>) => Effect<A2 | A, E2 | E, R2 | R>
  <A, E, R, A2, E2, R2>(self: Effect