Skip to content

Building Pipelines

Effect pipelines allow for the composition and sequencing of operations on values, enabling the transformation and manipulation of data in a concise and modular manner.

Pipelines are an excellent way to structure your application and handle data transformations in a concise and modular manner. They offer several benefits:

  1. Readability: Pipelines allow you to compose functions in a readable and sequential manner. You can clearly see the flow of data and the operations applied to it, making it easier to understand and maintain the code.

  2. Code Organization: With pipelines, you can break down complex operations into smaller, manageable functions. Each function performs a specific task, making your code more modular and easier to reason about.

  3. Reusability: Pipelines promote the reuse of functions. By breaking down operations into smaller functions, you can reuse them in different pipelines or contexts, improving code reuse and reducing duplication.

  4. Type Safety: By leveraging the type system, pipelines help catch errors at compile-time. Functions in a pipeline have well-defined input and output types, ensuring that the data flows correctly through the pipeline and minimizing runtime errors.

The use of functions in the Effect ecosystem libraries is important for achieving tree shakeability and ensuring extensibility. Functions enable efficient bundling by eliminating unused code, and they provide a flexible and modular approach to extending the libraries’ functionality.

Tree shakeability refers to the ability of a build system to eliminate unused code during the bundling process. Functions are tree shakeable, while methods are not.

When functions are used in the Effect ecosystem, only the functions that are actually imported and used in your application will be included in the final bundled code. Unused functions are automatically removed, resulting in a smaller bundle size and improved performance.

On the other hand, methods are attached to objects or prototypes, and they cannot be easily tree shaken. Even if you only use a subset of methods, all methods associated with an object or prototype will be included in the bundle, leading to unnecessary code bloat.

Another important advantage of using functions in the Effect ecosystem is the ease of extensibility. With methods, extending the functionality of an existing API often requires modifying the prototype of the object, which can be complex and error-prone.

In contrast, with functions, extending the functionality is much simpler. You can define your own “extension methods” as plain old functions without the need to modify the prototypes of objects. This promotes cleaner and more modular code, and it also allows for better compatibility with other libraries and modules.

The pipe function is a utility that allows us to compose functions in a readable and sequential manner. It takes the output of one function and passes it as the input to the next function in the pipeline. This enables us to build complex transformations by chaining multiple functions together.

Syntax

import { pipe } from "effect"
const result = pipe(input, func1, func2, ..., funcN)

In this syntax, input is the initial value, and func1, func2, …, funcN are the functions to be applied in sequence. The result of each function becomes the input for the next function, and the final result is returned.

Here’s an illustration of how pipe works:

┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌────────┐
│ input │───►│ func1 │───►│ func2 │───►│ ... │───►│ funcN │───►│ result │
└───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └────────┘

It’s important to note that functions passed to pipe must have a single argument because they are only called with a single argument.

Let’s see an example to better understand how pipe works:

Example (Chaining Arithmetic Operations)

1
import {
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
} from "effect"
2
3
// Define simple arithmetic operations
4
const
const increment: (x: number) => number
increment
= (
(parameter) x: number
x
: number) =>
(parameter) x: number
x
+ 1
5
const
const double: (x: number) => number
double
= (
(parameter) x: number
x
: number) =>
(parameter) x: number
x
* 2
6
const
const subtractTen: (x: number) => number
subtractTen
= (
(parameter) x: number
x
: number) =>
(parameter) x: number
x
- 10
7
8
// Sequentially apply these operations using `pipe`
9
const
const result: number
result
=
(alias) pipe<5, number, number, number>(a: 5, ab: (a: 5) => number, bc: (b: number) => number, cd: (c: number) => number): number (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(5,
const increment: (x: number) => number
increment
,
const double: (x: number) => number
double
,
const subtractTen: (x: number) => number
subtractTen
)
10
11
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(
const result: number
result
) // Output: 2

In the above example, we start with an input value of 5. The increment function adds 1 to the initial value, resulting in 6. Then, the double function doubles the value, giving us 12. Finally, the subtractTen function subtracts 10 from 12, resulting in the final output of 2.

The result is equivalent to subtractTen(double(increment(5))), but using pipe makes the code more readable because the operations are sequenced from left to right, rather than nesting them inside out.

The Effect.map function is used to transform the value inside an effect. It takes a function and applies it to the value contained within the effect, creating a new effect with the transformed value.

Syntax

const mappedEffect = pipe(myEffect, Effect.map(transformation))
// or
const mappedEffect = Effect.map(myEffect, transformation)
// or
const mappedEffect = myEffect.pipe(Effect.map(transformation))

In the code above, transformation is the function applied to the value, and myEffect is the effect being transformed.

Example (Adding a Service Charge)

Here’s a practical example where we apply a service charge to a transaction amount:

1
import {
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
,
import Effect
Effect
} from "effect"
2
3
// Function to add a small service charge to a transaction amount
4
const
const addServiceCharge: (amount: number) => number
addServiceCharge
= (
(parameter) amount: number
amount
: number) =>
(parameter) amount: number
amount
+ 1
5
6
// Simulated asynchronous task to fetch a transaction amount from database
7
const
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
=
import Effect
Effect
.
const promise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<number>(value: number): Promise<number> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
(100))
8
9
// Apply service charge to the transaction amount
10
const
const finalAmount: Effect.Effect<number, never, never>
finalAmount
=
(alias) pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>>(a: Effect.Effect<number, never, never>, ab: (a: Effect.Effect<number, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
11
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
,
12
import Effect
Effect
.
const map: <number, number>(f: (a: number) => number) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<number, E, R> (+1 overload)
map
(
const addServiceCharge: (amount: number) => number
addServiceCharge
)
13
)
14
15
import Effect
Effect
.
const runPromise: <number, never>(effect: Effect.Effect<number, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<number>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
const finalAmount: Effect.Effect<number, never, never>
finalAmount
).
(method) Promise<number>.then<void, never>(onfulfilled?: ((value: number) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
(
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
) // Output: 101

The Effect.as function is used to replace the original value inside an effect with a constant value.

Example (Replacing a Value)

1
import {
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
,
import Effect
Effect
} from "effect"
2
3
// Replace the value 5 with the constant "new value"
4
const
const program: Effect.Effect<string, never, never>
program
=
(alias) pipe<Effect.Effect<number, never, never>, Effect.Effect<string, never, never>>(a: Effect.Effect<number, never, never>, ab: (a: Effect.Effect<number, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(5),
import Effect
Effect
.
const as: <string>(value: string) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<string, E, R> (+1 overload)

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

as
("new value"))
5
6
import Effect
Effect
.
const runPromise: <string, never>(effect: Effect.Effect<string, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<string>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
const program: Effect.Effect<string, never, never>
program
).
(method) Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
(
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
) // Output: "new value"

The Effect.flatMap function is used when you need to chain transformations that produce Effect instances. This is useful for asynchronous operations or computations that depend on the results of previous effects.

This function allows you to sequence multiple effects, ensuring that each step results in a new Effect, “flattening” any nested structures that may arise.

Syntax

const flatMappedEffect = pipe(myEffect, Effect.flatMap(transformation))
// or
const flatMappedEffect = Effect.flatMap(myEffect, transformation)
// or
const flatMappedEffect = myEffect.pipe(Effect.flatMap(transformation))

In the code above, transformation is the function that takes a value and returns an Effect, and myEffect is the initial Effect being transformed.

Example (Applying a Discount)

1
import {
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
,
import Effect
Effect
} from "effect"
2
3
// Function to apply a discount safely to a transaction amount
4
const
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
= (
5
(parameter) total: number
total
: number,
6
(parameter) discountRate: number
discountRate
: number
7
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

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.

Effect
<number,
interface Error
Error
> =>
8
(parameter) discountRate: number
discountRate
=== 0
9
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
(new
var Error: ErrorConstructor new (message?: string) => Error
Error
("Discount rate cannot be zero"))
10
:
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) total: number
total
- (
(parameter) total: number
total
*
(parameter) discountRate: number
discountRate
) / 100)
11
12
// Simulated asynchronous task to fetch a transaction amount from database
13
const
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
=
import Effect
Effect
.
const promise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<number>(value: number): Promise<number> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
(100))
14
15
// Chaining the fetch and discount application using `flatMap`
16
const
const finalAmount: Effect.Effect<number, Error, never>
finalAmount
=
(alias) pipe<Effect.Effect<number, never, never>, Effect.Effect<number, Error, never>>(a: Effect.Effect<number, never, never>, ab: (a: Effect.Effect<number, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
17
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
,
18
import Effect
Effect
.
const flatMap: <number, number, Error, never>(f: (a: number) => Effect.Effect<number, Error, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<number, Error | E, R> (+1 overload)

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

flatMap
((
(parameter) amount: number
amount
) =>
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
(
(parameter) amount: number
amount
, 5))
19
)
20
21
import Effect
Effect
.
const runPromise: <number, Error>(effect: Effect.Effect<number, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<number>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
const finalAmount: Effect.Effect<number, Error, never>
finalAmount
).
(method) Promise<number>.then<void, never>(onfulfilled?: ((value: number) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
(
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
) // Output: 95

Make sure that all effects within Effect.flatMap contribute to the final computation. If you ignore an effect, it can lead to unexpected behavior:

Effect.flatMap((amount) => {
// This effect will be ignored
Effect.sync(() => console.log(`Apply a discount to: ${amount}`))
return applyDiscount(amount, 5)
})

In this case, the Effect.sync call is ignored and does not affect the result of applyDiscount(amount, 5). To handle effects correctly, make sure to explicitly chain them using functions like Effect.map, Effect.flatMap, Effect.andThen, or Effect.tap.

While developers may recognize flatMap from its use in arrays, in the Effect framework, it helps manage and flatten nested Effect structures. For instance, if you’re working with an effect that contains nested arrays (Effect<Array<Array<A>>>), you can flatten them like this:

1
import {
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
,
import Effect
Effect
,
import Array
Array
} from "effect"
2
3
const
const flattened: Effect.Effect<number[], never, never>
flattened
=
(alias) pipe<Effect.Effect<number[][], never, never>, Effect.Effect<number[], never, never>>(a: Effect.Effect<number[][], never, never>, ab: (a: Effect.Effect<number[][], never, never>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
4
import Effect
Effect
.
const succeed: <number[][]>(value: number[][]) => Effect.Effect<number[][], never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
([
5
[1, 2],
6
[3, 4]
7
]),
8
import Effect
Effect
.
const map: <number[][], number[]>(f: (a: number[][]) => number[]) => <E, R>(self: Effect.Effect<number[][], E, R>) => Effect.Effect<number[], E, R> (+1 overload)
map
((
(parameter) nested: number[][]
nested
) =>
import Array
Array
.
const flatten: <number[][]>(self: number[][]) => number[]

Combines multiple arrays into a single array by concatenating all elements from each nested array. This function ensures that the structure of nested arrays is collapsed into a single, flat array.

flatten
(
(parameter) nested: number[][]
nested
))
9
)

Alternatively, you can use JavaScript’s built-in Array.prototype.flat() method for array flattening.

The Effect.andThen function is a convenient tool for sequencing actions in Effect, combining both transformation scenarios handled by Effect.map and Effect.flatMap. It allows you to perform two actions, typically effects, where the second action may depend on the result of the first.

Syntax

const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect))
// or
const transformedEffect = Effect.andThen(myEffect, anotherEffect)
// or
const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect))

The anotherEffect action can take many forms:

  1. A value (similar to Effect.as)
  2. A function returning a value (similar to Effect.map)
  3. A Promise
  4. A function returning a Promise
  5. An Effect
  6. A function returning an Effect (similar to Effect.flatMap)

Example (Using andThen to Sequence Actions)

Let’s look at an example comparing Effect.andThen with Effect.map and Effect.flatMap:

1
import {
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
,
import Effect
Effect
} from "effect"
2
3
// Function to apply a discount safely to a transaction amount
4
const
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
= (
5
(parameter) total: number
total
: number,
6
(parameter) discountRate: number
discountRate
: number
7
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

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.

Effect
<number,
interface Error
Error
> =>
8
(parameter) discountRate: number
discountRate
=== 0
9
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
(new
var Error: ErrorConstructor new (message?: string) => Error
Error
("Discount rate cannot be zero"))
10
:
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) total: number
total
- (
(parameter) total: number
total
*
(parameter) discountRate: number
discountRate
) / 100)
11
12
// Simulated asynchronous task to fetch a transaction amount from database
13
const
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
=
import Effect
Effect
.
const promise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<number>(value: number): Promise<number> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
(100))
14
15
// Using Effect.map and Effect.flatMap
16
const
const result1: Effect.Effect<number, Error, never>
result1
=
(alias) pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>, Effect.Effect<number, Error, never>>(a: Effect.Effect<number, never, never>, ab: (a: Effect.Effect<...>) => Effect.Effect<...>, bc: (b: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
17
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
,
18
import Effect
Effect
.
const map: <number, number>(f: (a: number) => number) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<number, E, R> (+1 overload)
map
((
(parameter) amount: number
amount
) =>
(parameter) amount: number
amount
* 2),
19
import Effect
Effect
.
const flatMap: <number, number, Error, never>(f: (a: number) => Effect.Effect<number, Error, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<number, Error | E, R> (+1 overload)

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

flatMap
((
(parameter) amount: number
amount
) =>
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
(
(parameter) amount: number
amount
, 5))
20
)
21
22
import Effect
Effect
.
const runPromise: <number, Error>(effect: Effect.Effect<number, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<number>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
const result1: Effect.Effect<number, Error, never>
result1
).
(method) Promise<number>.then<void, never>(onfulfilled?: ((value: number) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
(
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
) // Output: 190
23
24
// Using Effect.andThen
25
const
const result2: Effect.Effect<number, Error, never>
result2
=
(alias) pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>, Effect.Effect<number, Error, never>>(a: Effect.Effect<number, never, never>, ab: (a: Effect.Effect<...>) => Effect.Effect<...>, bc: (b: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
26
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
,
27
import Effect
Effect
.
const andThen: <number, number>(f: (a: number) => number) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<number, E, R> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
((
(parameter) amount: number
amount
) =>
(parameter) amount: number
amount
* 2),
28
import Effect
Effect
.
const andThen: <number, Effect.Effect<number, Error, never>>(f: (a: number) => Effect.Effect<number, Error, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<...> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
((
(parameter) amount: number
amount
) =>
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
(
(parameter) amount: number
amount
, 5))
29
)
30
31
import Effect
Effect
.
const runPromise: <number, Error>(effect: Effect.Effect<number, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<number>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
const result2: Effect.Effect<number, Error, never>
result2
).
(method) Promise<number>.then<void, never>(onfulfilled?: ((value: number) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
(
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
) // Output: 190

Both Option and Either are commonly used for handling optional or missing values or simple error cases. These types integrate well with Effect.andThen. When used with Effect.andThen, the operations are categorized as scenarios 5 and 6 (as discussed earlier) because both Option and Either are treated as effects in this context.

Example (with Option)

1
import {
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
,
import Effect
Effect
,
import Option
Option
} from "effect"
2
3
// Simulated asynchronous task fetching a number from a database
4
const
const fetchNumberValue: Effect.Effect<number, UnknownException, never>
fetchNumberValue
=
import Effect
Effect
.
const tryPromise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, UnknownException, never> (+1 overload)

Creates an `Effect` that represents an asynchronous computation that might fail. If the `Promise` returned by `evaluate` rejects, the error is caught and the effect fails with an `UnknownException`. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API. **Overload with custom error handling:** Creates an `Effect` that represents an asynchronous computation that might fail, with custom error mapping. If the `Promise` rejects, the `catch` function maps the error to an error of type `E`.

tryPromise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<number>(value: number): Promise<number> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
(42))
5
6
// Effect<number, UnknownException | NoSuchElementException, never>
7
const
const program: Effect.Effect<number, UnknownException | NoSuchElementException, never>
program
=
(alias) pipe<Effect.Effect<number, UnknownException, never>, Effect.Effect<number, UnknownException | NoSuchElementException, never>>(a: Effect.Effect<...>, ab: (a: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
8
const fetchNumberValue: Effect.Effect<number, UnknownException, never>
fetchNumberValue
,
9
import Effect
Effect
.
const andThen: <number, Option.None<number> | Option.Some<number>>(f: (a: number) => Option.None<number> | Option.Some<number>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<...> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
((
(parameter) x: number
x
) => (
(parameter) x: number
x
> 0 ?
import Option
Option
.
const some: <number>(value: number) => Option.Option<number>

Creates a new `Option` that wraps the given value.

some
(
(parameter) x: number
x
) :
import Option
Option
.
const none: <never>() => Option.Option<never>

Creates a new `Option` that represents the absence of a value.

none
()))
10
)

You might expect the type of program to be Effect<Option<number>, UnknownException, never>, but it is actually Effect<number, UnknownException | NoSuchElementException, never>.

This is because Option<A> is treated as an effect of type Effect<A, NoSuchElementException>, and as a result, the possible errors are combined into a union type.

Example (with Either)

1
import {
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
,
import Effect
Effect
,
import Either
Either
} from "effect"
2
3
// Function to parse an integer from a string that can fail
4
const
const parseInteger: (input: string) => Either.Either<number, string>
parseInteger
= (
(parameter) input: string
input
: string):
import Either
Either
.
type Either<R, L = never> = Either.Left<L, R> | Either.Right<L, R> namespace Either
Either
<number, string> =>
5
function isNaN(number: number): boolean

Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).

isNaN
(
function parseInt(string: string, radix?: number): number

Converts a string to an integer.

parseInt
(
(parameter) input: string
input
))
6
?
import Either
Either
.
const left: <string>(left: string) => Either.Either<never, string>

Constructs a new `Either` holding a `Left` value. This usually represents a failure, due to the right-bias of this structure.

left
("Invalid integer")
7
:
import Either
Either
.
const right: <number>(right: number) => Either.Either<number, never>

Constructs a new `Either` holding a `Right` value. This usually represents a successful value due to the right bias of this structure.

right
(
function parseInt(string: string, radix?: number): number

Converts a string to an integer.

parseInt
(
(parameter) input: string
input
))
8
9
// Simulated asynchronous task fetching a string from database
10
const
const fetchStringValue: Effect.Effect<string, UnknownException, never>
fetchStringValue
=
import Effect
Effect
.
const tryPromise: <string>(evaluate: (signal: AbortSignal) => PromiseLike<string>) => Effect.Effect<string, UnknownException, never> (+1 overload)

Creates an `Effect` that represents an asynchronous computation that might fail. If the `Promise` returned by `evaluate` rejects, the error is caught and the effect fails with an `UnknownException`. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API. **Overload with custom error handling:** Creates an `Effect` that represents an asynchronous computation that might fail, with custom error mapping. If the `Promise` rejects, the `catch` function maps the error to an error of type `E`.

tryPromise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<string>(value: string): Promise<string> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
("42"))
11
12
// Effect<number, string | UnknownException, never>
13
const
const program: Effect.Effect<number, string | UnknownException, never>
program
=
(alias) pipe<Effect.Effect<string, UnknownException, never>, Effect.Effect<number, string | UnknownException, never>>(a: Effect.Effect<string, UnknownException, never>, ab: (a: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
14
const fetchStringValue: Effect.Effect<string, UnknownException, never>
fetchStringValue
,
15
import Effect
Effect
.
const andThen: <string, Either.Either<number, string>>(f: (a: string) => Either.Either<number, string>) => <E, R>(self: Effect.Effect<string, E, R>) => Effect.Effect<number, string | E, R> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
((
(parameter) str: string
str
) =>
const parseInteger: (input: string) => Either.Either<number, string>
parseInteger
(
(parameter) str: string
str
))
16
)

Although one might expect the type of program to be Effect<Either<number, string>, UnknownException, never>, it is actually Effect<number, string | UnknownException, never>.

This is because Either<A, E> is treated as an effect of type Effect<A, E>, meaning the errors are combined into a union type.

The Effect.tap function works similarly to Effect.flatMap, but with a key difference: the successful result of the function passed to tap is ignored. This means the value from the previous computation remains available for the next step in the chain.

Example (Logging a Discount Application)

1
import {
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
,
import Effect
Effect
} from "effect"
2
3
// Function to apply a discount safely to a transaction amount
4
const
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
= (
5
(parameter) total: number
total
: number,
6
(parameter) discountRate: number
discountRate
: number
7
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

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.

Effect
<number,
interface Error
Error
> =>
8
(parameter) discountRate: number
discountRate
=== 0
9
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
(new
var Error: ErrorConstructor new (message?: string) => Error
Error
("Discount rate cannot be zero"))
10
:
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) total: number
total
- (
(parameter) total: number
total
*
(parameter) discountRate: number
discountRate
) / 100)
11
12
// Simulated asynchronous task to fetch a transaction amount from database
13
const
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
=
import Effect
Effect
.
const promise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<number>(value: number): Promise<number> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
(100))
14
15
const
const finalAmount: Effect.Effect<number, Error, never>
finalAmount
=
(alias) pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>, Effect.Effect<number, Error, never>>(a: Effect.Effect<number, never, never>, ab: (a: Effect.Effect<...>) => Effect.Effect<...>, bc: (b: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
16
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
,
17
// Log the fetched transaction amount
18
import Effect
Effect
.
const tap: <number, Effect.Effect<void, never, never>>(f: (a: number) => Effect.Effect<void, never, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<...> (+7 overloads)
tap
((
(parameter) amount: number
amount
) =>
19
import Effect
Effect
.
const sync: <void>(thunk: LazyArg<void>) => Effect.Effect<void, never, never>

Creates an `Effect` that represents a synchronous side-effectful computation. The provided function (`thunk`) should not throw errors; if it does, the error is treated as a defect. Use `Effect.sync` when you are certain the operation will not fail.

sync
(() =>
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(`Apply a discount to: ${
(parameter) amount: number
amount
}`))
20
),
21
// `amount` is still available!
22
import Effect
Effect
.
const flatMap: <number, number, Error, never>(f: (a: number) => Effect.Effect<number, Error, never>) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<number, Error | E, R> (+1 overload)

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

flatMap
((
(parameter) amount: number
amount
) =>
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
(
(parameter) amount: number
amount
, 5))
23
)
24
25
import Effect
Effect
.
const runPromise: <number, Error>(effect: Effect.Effect<number, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<number>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
const finalAmount: Effect.Effect<number, Error, never>
finalAmount
).
(method) Promise<number>.then<void, never>(onfulfilled?: ((value: number) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
(
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
)
26
/*
27
Output:
28
Apply a discount to: 100
29
95
30
*/

In this example, Effect.tap is used to log the transaction amount before applying the discount, without modifying the value itself. The original value (amount) remains available for the next operation (applyDiscount).

Using Effect.tap allows us to execute side effects during the computation without altering the result. This can be useful for logging, performing additional actions, or observing the intermediate values without interfering with the main computation flow.

The Effect.all function lets you combine multiple effects into a single effect. This new effect will produce a tuple containing the results of all the individual effects.

Syntax

const combinedEffect = Effect.all([effect1, effect2, ...])

By default the Effect.all function executes all the provided effects sequentially (to explore options for managing concurrency and controlling how these effects are executed, you can refer to the Concurrency Options documentation).

Each effect runs in order, and the function returns a new effect that contains the results of the original effects as a tuple.

The results in the tuple follow the same order as the effects passed to Effect.all.

Example (Combining Configuration and Database Checks)

1
import {
import Effect
Effect
} from "effect"
2
3
// Simulated function to read configuration from a file
4
const
const webConfig: Effect.Effect<{ dbConnection: string; port: number; }, never, never>
webConfig
=
import Effect
Effect
.
const promise: <{ dbConnection: string; port: number; }>(evaluate: (signal: AbortSignal) => PromiseLike<{ dbConnection: string; port: number; }>) => Effect.Effect<{ dbConnection: string; port: number; }, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
5
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<{ dbConnection: string; port: number; }>(value: { dbConnection: string; port: number; }): Promise<{ dbConnection: string; port: number; }> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
({
(property) dbConnection: string
dbConnection
: "localhost",
(property) port: number
port
: 8080 })
6
)
7
8
// Simulated function to test database connectivity
9
const
const checkDatabaseConnectivity: Effect.Effect<string, never, never>
checkDatabaseConnectivity
=
import Effect
Effect
.
const promise: <string>(evaluate: (signal: AbortSignal) => PromiseLike<string>) => Effect.Effect<string, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
10
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<string>(value: string): Promise<string> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
("Connected to Database")
11
)
12
13
// Combine both effects to perform startup checks
14
const
const startupChecks: Effect.Effect<[{ dbConnection: string; port: number; }, string], never, never>
startupChecks
=
import Effect
Effect
.
const all: <readonly [Effect.Effect<{ dbConnection: string; port: number; }, never, never>, Effect.Effect<string, never, never>], { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined; readonly discard?: boolean | undefined; readonly mode?: "default" | "validate" | "either" | undefined; readonly concurrentFinalizers?: boolean | undefined; }>(arg: readonly [...], options?: { ...; } | undefined) => Effect.Effect<...>

Runs all the provided effects in sequence respecting the structure provided in input. Supports multiple arguments, a single argument tuple / array or record / struct.

all
([
const webConfig: Effect.Effect<{ dbConnection: string; port: number; }, never, never>
webConfig
,
const checkDatabaseConnectivity: Effect.Effect<string, never, never>
checkDatabaseConnectivity
])
15
16
import Effect
Effect
.
const runPromise: <[{ dbConnection: string; port: number; }, string], never>(effect: Effect.Effect<[{ dbConnection: string; port: number; }, string], never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
const startupChecks: Effect.Effect<[{ dbConnection: string; port: number; }, string], never, never>
startupChecks
).
(method) Promise<[{ dbConnection: string; port: number; }, string]>.then<void, never>(onfulfilled?: ((value: [{ dbConnection: string; port: number; }, string]) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
(([
(parameter) config: { dbConnection: string; port: number; }
config
,
(parameter) dbStatus: string
dbStatus
]) => {
17
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(
18
`Configuration: ${
var JSON: JSON

An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.

JSON
.
(method) JSON.stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string (+1 overload)

Converts a JavaScript value to a JavaScript Object Notation (JSON) string.

stringify
(
(parameter) config: { dbConnection: string; port: number; }
config
)}\nDB Status: ${
(parameter) dbStatus: string
dbStatus
}`
19
)
20
})
21
/*
22
Output:
23
Configuration: {"dbConnection":"localhost","port":8080}
24
DB Status: Connected to Database
25
*/

Let’s now combine the pipe function, Effect.all, and Effect.andThen to create a pipeline that performs a sequence of transformations.

Example (Building a Transaction Pipeline)

1
import {
import Effect
Effect
,
(alias) function pipe<A>(a: A): A (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
} from "effect"
2
3
// Function to add a small service charge to a transaction amount
4
const
const addServiceCharge: (amount: number) => number
addServiceCharge
= (
(parameter) amount: number
amount
: number) =>
(parameter) amount: number
amount
+ 1
5
6
// Function to apply a discount safely to a transaction amount
7
const
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
= (
8
(parameter) total: number
total
: number,
9
(parameter) discountRate: number
discountRate
: number
10
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

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.

Effect
<number,
interface Error
Error
> =>
11
(parameter) discountRate: number
discountRate
=== 0
12
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
(new
var Error: ErrorConstructor new (message?: string) => Error
Error
("Discount rate cannot be zero"))
13
:
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) total: number
total
- (
(parameter) total: number
total
*
(parameter) discountRate: number
discountRate
) / 100)
14
15
// Simulated asynchronous task to fetch a transaction amount from database
16
const
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
=
import Effect
Effect
.
const promise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<number>(value: number): Promise<number> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
(100))
17
18
// Simulated asynchronous task to fetch a discount rate
19
// from a configuration file
20
const
const fetchDiscountRate: Effect.Effect<number, never, never>
fetchDiscountRate
=
import Effect
Effect
.
const promise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<number>(value: number): Promise<number> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
(5))
21
22
// Assembling the program using a pipeline of effects
23
const
const program: Effect.Effect<string, Error, never>
program
=
(alias) pipe<Effect.Effect<[number, number], never, never>, Effect.Effect<number, Error, never>, Effect.Effect<number, Error, never>, Effect.Effect<string, Error, never>>(a: Effect.Effect<...>, ab: (a: Effect.Effect<...>) => Effect.Effect<...>, bc: (b: Effect.Effect<...>) => Effect.Effect<...>, cd: (c: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+19 overloads) import pipe

Pipes the value of an expression into a pipeline of functions. This is useful in combination with data-last functions as a simulation of methods: ``` as.map(f).filter(g) -> pipe(as, map(f), filter(g)) ```

pipe
(
24
// Combine both fetch effects to get the transaction amount
25
// and discount rate
26
import Effect
Effect
.
const all: <readonly [Effect.Effect<number, never, never>, Effect.Effect<number, never, never>], { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined; readonly discard?: boolean | undefined; readonly mode?: "default" | "validate" | "either" | undefined; readonly concurrentFinalizers?: boolean | undefined; }>(arg: readonly [...], options?: { ...; } | undefined) => Effect.Effect<...>

Runs all the provided effects in sequence respecting the structure provided in input. Supports multiple arguments, a single argument tuple / array or record / struct.

all
([
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
,
const fetchDiscountRate: Effect.Effect<number, never, never>
fetchDiscountRate
]),
27
28
// Apply the discount to the transaction amount
29
import Effect
Effect
.
const andThen: <[number, number], Effect.Effect<number, Error, never>>(f: (a: [number, number]) => Effect.Effect<number, Error, never>) => <E, R>(self: Effect.Effect<[number, number], E, R>) => Effect.Effect<...> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
(([
(parameter) transactionAmount: number
transactionAmount
,
(parameter) discountRate: number
discountRate
]) =>
30
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
(
(parameter) transactionAmount: number
transactionAmount
,
(parameter) discountRate: number
discountRate
)
31
),
32
33
// Add the service charge to the discounted amount
34
import Effect
Effect
.
const andThen: <number, number>(f: (a: number) => number) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<number, E, R> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
(
const addServiceCharge: (amount: number) => number
addServiceCharge
),
35
36
// Format the final result for display
37
import Effect
Effect
.
const andThen: <number, string>(f: (a: number) => string) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<string, E, R> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
(
38
(
(parameter) finalAmount: number
finalAmount
) => `Final amount to charge: ${
(parameter) finalAmount: number
finalAmount
}`
39
)
40
)
41
42
// Execute the program and log the result
43
import Effect
Effect
.
const runPromise: <string, Error>(effect: Effect.Effect<string, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<string>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
const program: Effect.Effect<string, Error, never>
program
).
(method) Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

Attaches callbacks for the resolution and/or rejection of the Promise.

then
(
namespace console var console: Console

The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```

console
.
(method) Console.log(message?: any, ...optionalParams: any[]): void

Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
)
44
// Output: "Final amount to charge: 96"

This pipeline demonstrates how you can structure your code by combining different effects into a clear, readable flow.

Effect provides a pipe method that works similarly to the pipe method found in rxjs. This method allows you to chain multiple operations together, making your code more concise and readable.

Syntax

const result = effect.pipe(func1, func2, ..., funcN)

This is equivalent to using the pipe function like this:

const result = pipe(effect, func1, func2, ..., funcN)

The pipe method is available on all effects and many other data types, eliminating the need to import the pipe function and saving you some keystrokes.

Example (Using the pipe Method)

Let’s rewrite an earlier example, this time using the pipe method.

1
import {
import Effect
Effect
} from "effect"
2
13 collapsed lines
3
const
const addServiceCharge: (amount: number) => number
addServiceCharge
= (
(parameter) amount: number
amount
: number) =>
(parameter) amount: number
amount
+ 1
4
5
const
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
= (
6
(parameter) total: number
total
: number,
7
(parameter) discountRate: number
discountRate
: number
8
):
import Effect
Effect
.
interface Effect<out A, out E = never, out R = never> namespace Effect

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.

Effect
<number,
interface Error
Error
> =>
9
(parameter) discountRate: number
discountRate
=== 0
10
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>

Creates an `Effect` that represents a recoverable error. This `Effect` does not succeed but instead fails with the provided error. The failure can be of any type, and will propagate through the effect pipeline unless handled. Use this function when you want to explicitly signal an error in an `Effect` computation. The failed effect can later be handled with functions like {@link catchAll } or {@link catchTag } .

fail
(new
var Error: ErrorConstructor new (message?: string) => Error
Error
("Discount rate cannot be zero"))
11
:
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
(
(parameter) total: number
total
- (
(parameter) total: number
total
*
(parameter) discountRate: number
discountRate
) / 100)
12
13
const
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
=
import Effect
Effect
.
const promise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<number>(value: number): Promise<number> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
(100))
14
15
const
const fetchDiscountRate: Effect.Effect<number, never, never>
fetchDiscountRate
=
import Effect
Effect
.
const promise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, never, never>

Creates an `Effect` that represents an asynchronous computation guaranteed to succeed. The provided function (`thunk`) returns a `Promise` that should never reject. If the `Promise` does reject, the rejection is treated as a defect. An optional `AbortSignal` can be provided to allow for interruption of the wrapped `Promise` API.

promise
(() =>
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
(method) PromiseConstructor.resolve<number>(value: number): Promise<number> (+2 overloads)

Creates a new resolved promise for the provided value.

resolve
(5))
16
17
const
const program: Effect.Effect<string, Error, never>
program
=
import Effect
Effect
.
const all: <readonly [Effect.Effect<number, never, never>, Effect.Effect<number, never, never>], { readonly concurrency?: Concurrency | undefined; readonly batching?: boolean | "inherit" | undefined; readonly discard?: boolean | undefined; readonly mode?: "default" | "validate" | "either" | undefined; readonly concurrentFinalizers?: boolean | undefined; }>(arg: readonly [...], options?: { ...; } | undefined) => Effect.Effect<...>

Runs all the provided effects in sequence respecting the structure provided in input. Supports multiple arguments, a single argument tuple / array or record / struct.

all
([
18
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
,
19
const fetchDiscountRate: Effect.Effect<number, never, never>
fetchDiscountRate
20
]).
(method) Pipeable.pipe<Effect.Effect<[number, number], never, never>, Effect.Effect<number, Error, never>, Effect.Effect<number, Error, never>, Effect.Effect<string, Error, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Effect.Effect<...>, bc: (_: Effect.Effect<...>) => Effect.Effect<...>, cd: (_: Effect.Effect<...>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe
(
21
import Effect
Effect
.
const andThen: <[number, number], Effect.Effect<number, Error, never>>(f: (a: [number, number]) => Effect.Effect<number, Error, never>) => <E, R>(self: Effect.Effect<[number, number], E, R>) => Effect.Effect<...> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
(([
(parameter) transactionAmount: number
transactionAmount
,
(parameter) discountRate: number
discountRate
]) =>
22
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
(
(parameter) transactionAmount: number
transactionAmount
,
(parameter) discountRate: number
discountRate
)
23
),
24
import Effect
Effect
.
const andThen: <number, number>(f: (a: number) => number) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<number, E, R> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
(
const addServiceCharge: (amount: number) => number
addServiceCharge
),
25
import Effect
Effect
.
const andThen: <number, string>(f: (a: number) => string) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<string, E, R> (+3 overloads)

Executes a sequence of two actions, typically two `Effect`s, 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

andThen
(
26
(
(parameter) finalAmount: number
finalAmount
) => `Final amount to charge: ${
(parameter) finalAmount: number
finalAmount
}`
27
)
28
)

Let’s summarize the transformation functions we have seen so far:

APIInputOutput
mapEffect<A, E, R>, A => BEffect<B, E, R>
flatMapEffect<A, E, R>, A => Effect<B, E, R>Effect<B, E, R>
andThenEffect<A, E, R>, *Effect<B, E, R>
tapEffect<A, E, R>, A => Effect<B, E, R>Effect<A, E, R>
all[Effect<A, E, R>, Effect<B, E, R>, ...]Effect<[A, B, ...], E, R>