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.

The basic syntax of pipe is as follows:

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:

Effect Pipelines

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:

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.

The syntax for Effect.map is as follows:

import { pipe, Effect } from "effect"
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

Consider a program that adds a small service charge to a transaction:

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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an 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

To map an Effect to a constant value, replacing the original value, use Effect.as:

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
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>
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"))
4
5
import Effect
Effect
.
const runPromise: <string, never>(effect: Effect.Effect<string, never, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<string>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an 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.

The Effect.flatMap function enables you to sequence computations that result in new Effect values, “flattening” any nested effect structures that arise.

The syntax for Effect.flatMap is as follows:

import { pipe, Effect } from "effect"
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

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>
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>
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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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, 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
(
16
const fetchTransactionAmount: Effect.Effect<number, never, never>
fetchTransactionAmount
,
17
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))
18
)
19
20
import Effect
Effect
.
const runPromise: <number, Error>(effect: Effect.Effect<number, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<number>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an 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

Ensuring All Effects Are Considered

It’s vital to ensure that all effects within Effect.flatMap contribute to the final computation. Neglecting any effect can lead to unexpected behaviors or incorrect outcomes:

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

The Effect.sync above is ignored and does not influence the result of applyDiscount(amount, 5). To include effects properly and avoid errors, explicitly chain them using functions like Effect.map, Effect.flatMap, Effect.andThen, or Effect.tap.

Further Information on flatMap

Although many developers may recognize flatMap from its usage with arrays, in the Effect framework, it’s utilized to manage and resolve nested Effect structures. If your goal is to flatten nested arrays within an Effect (Effect<Array<Array<A>>>), this can be done using:

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>
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
)

or using the standard Array.prototype.flat() method.

Both the Effect.map and Effect.flatMap functions serve to transform an effect into another effect in two different scenarios. In the first scenario, Effect.map is used when the transformation function does not return an effect, while in the second scenario, Effect.flatMap is used when the transformation function still returns an effect.

However, since both scenarios involve transformations, the Effect module also exposes a convenient all-in-one solution to use: Effect.andThen.

The Effect.andThen function executes a sequence of two actions, typically two effects, where the second action can depend on the result of the first action.

import { pipe, Effect } from "effect"
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 various forms:

  1. a value (i.e. same functionality of Effect.as)
  2. a function returning a value (i.e. same functionality of Effect.map)
  3. a Promise
  4. a function returning a Promise
  5. an Effect
  6. a function returning an Effect(i.e. same functionality of Effect.flatMap)

Example

Let’s see an example where we can compare the use of Effect.andThen instead of 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>
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>
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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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, 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>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an 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>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an 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

It’s worth noting that Option and Either, types commonly used to handle optional values and simple error scenarios, are also compatible with Effect.andThen. However, it is important to understand that when these types are used, the operations are categorized under scenarios 5 and 6 as described previously, as both Option and Either operate 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, never, never>
fetchNumberValue
=
import Effect
Effect
.
const promise: <number>(evaluate: (signal: AbortSignal) => PromiseLike<number>) => Effect.Effect<number, never, never>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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
(42))
5
6
// Although one might expect the type to be
7
// Effect<Option<number>, never, never>, it is actually
8
// Effect<number, NoSuchElementException, never>
9
const
const program: Effect.Effect<number, NoSuchElementException, never>
program
=
(alias) pipe<Effect.Effect<number, never, never>, Effect.Effect<number, NoSuchElementException, never>>(a: Effect.Effect<number, never, 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
(
10
const fetchNumberValue: Effect.Effect<number, never, never>
fetchNumberValue
,
11
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
()))
12
)

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, never, never>
fetchStringValue
=
import Effect
Effect
.
const promise: <string>(evaluate: (signal: AbortSignal) => PromiseLike<string>) => Effect.Effect<string, never, never>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

promise
(() =>
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
// Although one might expect the type to be
13
// Effect<Either<number, string>, never, never>, it is actually
14
// Effect<number, string, never>
15
const
const program: Effect.Effect<number, string, never>
program
=
(alias) pipe<Effect.Effect<string, never, never>, Effect.Effect<number, string, never>>(a: Effect.Effect<string, never, never>, ab: (a: Effect.Effect<string, 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
(
16
const fetchStringValue: Effect.Effect<string, never, never>
fetchStringValue
,
17
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
))
18
)

The Effect.tap API has a similar signature to Effect.flatMap, but the result of the transformation function is ignored. This means that the value returned by the previous computation will still be available for the next computation.

Example

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>
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>
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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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
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
) =>
18
import Effect
Effect
.
const sync: <void>(evaluate: LazyArg<void>) => Effect.Effect<void, never, never>
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
}`))
19
),
20
// `amount` is still available!
21
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))
22
)
23
24
import Effect
Effect
.
const runPromise: <number, Error>(effect: Effect.Effect<number, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<number>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an 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
)
25
/*
26
Output:
27
Apply a discount to: 100
28
95
29
*/

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 is a powerful utility provided by Effect that allows you to combine multiple effects into a single effect that produces a tuple of results.

The syntax for Effect.all is as follows:

import { Effect } from "effect"
const combinedEffect = Effect.all([effect1, effect2, ...])

The Effect.all function will execute all these effects in sequence (to explore options for managing concurrency and controlling how these effects are executed, you can refer to the Concurrency Options documentation).

It will return a new effect that produces a tuple containing the results of each individual effect. Keep in mind that the order of the results corresponds to the order of the original effects passed to Effect.all.

Example

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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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<...>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an 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
*/

Now, let’s combine pipe, Effect.all and Effect.andThen to build a pipeline that performs a series of transformations:

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>
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>
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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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
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
]),
25
import Effect
Effect
.
const flatMap: <[number, number], number, Error, never>(f: (a: [number, number]) => Effect.Effect<number, Error, never>) => <E, R>(self: Effect.Effect<[number, number], E, R>) => Effect.Effect<...> (+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) transactionAmount: number
transactionAmount
,
(parameter) discountRate: number
discountRate
]) =>
26
const applyDiscount: (total: number, discountRate: number) => Effect.Effect<number, Error>
applyDiscount
(
(parameter) transactionAmount: number
transactionAmount
,
(parameter) discountRate: number
discountRate
)
27
),
28
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
),
29
import Effect
Effect
.
const map: <number, string>(f: (a: number) => string) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<string, E, R> (+1 overload)
map
((
(parameter) finalAmount: number
finalAmount
) => `Final amount to charge: ${
(parameter) finalAmount: number
finalAmount
}`)
30
)
31
32
// Execute the program and log the result
33
import Effect
Effect
.
const runPromise: <string, Error>(effect: Effect.Effect<string, Error, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<string>

Runs an `Effect` workflow, returning a `Promise` which resolves with the result of the workflow or rejects with an 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
)
34
// Output: "Final amount to charge: 96"

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.

Here’s how the pipe method works:

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 from the Function module and saving you some keystrokes.

Let’s rewrite the previous example 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>
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>
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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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>

Like `tryPromise` but produces a defect in case of errors. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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 flatMap: <[number, number], number, Error, never>(f: (a: [number, number]) => Effect.Effect<number, Error, never>) => <E, R>(self: Effect.Effect<[number, number], E, R>) => Effect.Effect<...> (+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) 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 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
),
25
import Effect
Effect
.
const map: <number, string>(f: (a: number) => string) => <E, R>(self: Effect.Effect<number, E, R>) => Effect.Effect<string, E, R> (+1 overload)
map
((
(parameter) finalAmount: number
finalAmount
) => `Final amount to charge: ${
(parameter) finalAmount: number
finalAmount
}`)
26
)

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>