Creating Effects
Effect provides different ways to create effects, which are units of computation that encapsulate side effects. In this guide, we will cover some of the common methods that you can use to create effects.
In traditional programming, when an error occurs, it is often handled by throwing an exception:
1const const divide: (a: number, b: number) => number
divide = ((parameter) a: number
a: number, (parameter) b: number
b: number): number => {2 if ((parameter) b: number
b === 0) {3 throw new var Error: ErrorConstructor
new (message?: string) => Error
Error("Cannot divide by zero")4 }5 return (parameter) a: number
a / (parameter) b: number
b6}
However, throwing errors can be problematic. The type signatures of functions do not indicate that they can throw exceptions, making it difficult to reason about potential errors.
To address this issue, Effect introduces dedicated constructors for creating effects that represent both success and failure: Effect.succeed
and Effect.fail
. These constructors allow you to explicitly handle success and failure cases while leveraging the type system to track errors.
The Effect.succeed
constructor is used to create an effect that will always succeed.
Example (Creating a Successful Effect)
1import { import Effect
Effect } from "effect"2
3// Creating an effect that represents a successful scenario4const const success: Effect.Effect<number, never, never>
success = 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(42)
The type of success
is Effect<number, never, never>
, which means:
- It produces a value of type
number
. - It does not generate any errors (
never
indicates no errors). - It requires no additional data or dependencies (
never
indicates no requirements).
┌─── Produces a value of type number │ ┌─── Does not generate any errors │ │ ┌─── Requires no dependencies ▼ ▼ ▼Effect<number, never, never>
When a computation may fail, it’s important to manage failure explicitly. The Effect.fail
constructor allows you to represent an error in a type-safe way.
Example (Creating a Failed Effect)
1import { import Effect
Effect } from "effect"2
3// Creating an effect that represents a failure scenario4const const failure: Effect.Effect<never, Error, never>
failure = 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(5 new var Error: ErrorConstructor
new (message?: string) => Error
Error("Operation failed due to network error")6)
The type of failure
is Effect<never, Error, never>
, which means:
- It never produces a value (
never
indicates that no successful result will be produced). - It fails with an error, specifically an
Error
. - It requires no additional data or dependencies (
never
indicates no requirements).
┌─── Never produces a value │ ┌─── Fails with an Error │ │ ┌─── Requires no dependencies ▼ ▼ ▼Effect<never, Error, never>
Although you can use Error
objects with Effect.fail
, you can also pass strings, numbers, or more complex objects depending on your error management strategy.
Using “tagged” errors (objects with a _tag
field) can help identify error types and works well with standard Effect functions, like Effect.catchTag.
Example (Using Tagged Errors)
1import { import Effect
Effect } from "effect"2
3class class HttpError
HttpError {4 readonly (property) HttpError._tag: "HttpError"
_tag = "HttpError"5}6
7const const program: Effect.Effect<never, HttpError, never>
program = import Effect
Effect.const fail: <HttpError>(error: HttpError) => Effect.Effect<never, HttpError, 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 constructor HttpError(): HttpError
HttpError())
With Effect.succeed
and Effect.fail
, you can explicitly handle success and failure cases and the type system will ensure that errors are tracked and accounted for.
Example (Rewriting a Division Function)
Here’s how you can rewrite the divide
function using Effect, making error handling explicit.
1import { import Effect
Effect } from "effect"2
3const const divide: (a: number, b: number) => Effect.Effect<number, Error>
divide = ((parameter) a: number
a: number, (parameter) b: number
b: number): 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> =>4 (parameter) b: number
b === 05 ? 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("Cannot divide by zero"))6 : 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) a: number
a / (parameter) b: number
b)
In this example, the divide
function indicates in its return type Effect<number, Error>
that the operation can either succeed with a number
or fail with an Error
.
┌─── Produces a value of type number │ ┌─── Fails with an Error ▼ ▼Effect<number, Error>
This clear type signature helps ensure that errors are handled properly and that anyone calling the function is aware of the possible outcomes.
Example (Simulating a User Retrieval Operation)
Let’s imagine another scenario where we use Effect.succeed
and Effect.fail
to model a simple user retrieval operation where the user data is hardcoded, which could be useful in testing scenarios or when mocking data:
1import { import Effect
Effect } from "effect"2
3// Define a User type4interface interface User
User {5 readonly (property) User.id: number
id: number6 readonly (property) User.name: string
name: string7}8
9// A mocked function to simulate fetching a user from a database10const const getUser: (userId: number) => Effect.Effect<User, Error>
getUser = ((parameter) userId: number
userId: number): 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<interface User
User, interface Error
Error> => {11 // Normally, you would access a database or API here, but we'll mock it12 const const userDatabase: Record<number, User>
userDatabase: type Record<K extends keyof any, T> = { [P in K]: T; }
Construct a type with a set of properties K of type T
Record<number, interface User
User> = {13 1: { (property) User.id: number
id: 1, (property) User.name: string
name: "John Doe" },14 2: { (property) User.id: number
id: 2, (property) User.name: string
name: "Jane Smith" }15 }16
17 // Check if the user exists in our "database" and return appropriately18 const const user: User
user = const userDatabase: Record<number, User>
userDatabase[(parameter) userId: number
userId]19 if (const user: User
user) {20 return import Effect
Effect.const succeed: <User>(value: User) => Effect.Effect<User, 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(const user: User
user)21 } else {22 return 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("User not found"))23 }24}25
26// When executed, this will successfully return the user with id 127const const exampleUserEffect: Effect.Effect<User, Error, never>
exampleUserEffect = const getUser: (userId: number) => Effect.Effect<User, Error>
getUser(1)
In this example, exampleUserEffect
, which has the type Effect<User, Error>
, will either produce a User
object or an Error
, depending on whether the user exists in the mocked database.
For a deeper dive into managing errors in your applications, refer to the Error Management Guide.
In JavaScript, you can delay the execution of synchronous computations using “thunks”.
Thunks are useful for delaying the computation of a value until it is needed.
To model synchronous side effects, Effect provides the Effect.sync
and Effect.try
constructors, which accept a thunk.
When working with side effects that are synchronous — meaning they don’t involve asynchronous operations like fetching data from the internet — you can use the Effect.sync
function.
This function is ideal when you are certain these operations won’t produce any errors.
Example (Logging a Message)
1import { import Effect
Effect } from "effect"2
3const const log: (message: string) => Effect.Effect<void, never, never>
log = ((parameter) message: string
message: string) =>4 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(() => {5 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((parameter) message: string
message) // side effect6 })7
8const const program: Effect.Effect<void, never, never>
program = const log: (message: string) => Effect.Effect<void, never, never>
log("Hello, World!")
In the above example, Effect.sync
is used to defer the side-effect of writing to the console.
Important Notes:
- Execution: The side effect (logging to the console) encapsulated within
program
won’t occur until the effect is explicitly run. This allows you to define side effects at one point in your code and control when they are activated, improving manageability and predictability of side effects in larger applications. - Error Handling: It’s crucial that the function you pass to
Effect.sync
does not throw any errors. If you anticipate potential errors, consider using try instead, which handles errors gracefully.
Handling Unexpected Errors. Despite your best efforts to avoid errors in the function passed to Effect.sync
, if an error does occur, it results in a “defect”.
This defect is not a standard error but indicates a flaw in the logic that was expected to be error-free.
You can think of it similar to an unexpected crash in the program, which can be further managed or logged using tools like Effect.catchAllDefect.
This feature ensures that even unexpected failures in your application are not lost and can be handled appropriately.
In situations where you need to perform synchronous operations that might fail, such as parsing JSON, you can use the Effect.try
constructor from the Effect library.
This constructor is designed to handle operations that could throw exceptions by capturing those exceptions and transforming them into manageable errors within the Effect framework.
Example (Safe JSON Parsing)
Suppose you have a function that attempts to parse a JSON string. This operation can fail and throw an error if the input string is not properly formatted as JSON:
1import { import Effect
Effect } from "effect"2
3const const parse: (input: string) => Effect.Effect<any, UnknownException, never>
parse = ((parameter) input: string
input: string) =>4 // This might throw an error if input is not valid JSON5 import Effect
Effect.(alias) try<any>(thunk: LazyArg<any>): Effect.Effect<any, UnknownException, never> (+1 overload)
export try
try(() => 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.parse(text: string, reviver?: (this: any, key: string, value: any) => any): any
Converts a JavaScript Object Notation (JSON) string into an object.
parse((parameter) input: string
input))6
7const const program: Effect.Effect<any, UnknownException, never>
program = const parse: (input: string) => Effect.Effect<any, UnknownException, never>
parse("")
In this example:
parse
is a function that creates an effect encapsulating the JSON parsing operation.- If
JSON.parse(input)
throws an error due to invalid input,Effect.try
catches this error and the effect represented byprogram
will fail with anUnknownException
. This ensures that errors are not silently ignored but are instead handled within the structured flow of effects.
You might want to transform the caught exception into a more specific error or perform additional operations when catching an error. Effect.try
supports an overload that allows you to specify how caught exceptions should be transformed:
Example (Custom Error Handling)
1import { Effect } from "effect"2
3const parse = (input: string) =>4 Effect.try({5 // JSON.parse may throw for bad input6 try: () => JSON.parse(input),7 // remap the error8 catch: (unknown) => new Error(`something went wrong ${unknown}`)9 })10
11const program = parse("")
You can think of this as a similar pattern to the traditional try-catch block in JavaScript:
try { return JSON.parse(input)} catch (unknown) { throw new Error(`something went wrong ${unknown}`)}
In traditional programming, we often use Promise
s to handle asynchronous computations. However, dealing with errors in promises can be problematic. By default, Promise<Value>
only provides the type Value
for the resolved value, which means errors are not reflected in the type system. This limits the expressiveness and makes it challenging to handle and track errors effectively.
To overcome these limitations, Effect introduces dedicated constructors for creating effects that represent both success and failure in an asynchronous context: Effect.promise
and Effect.tryPromise
. These constructors allow you to explicitly handle success and failure cases while leveraging the type system to track errors.
This constructor is similar to a regular Promise
, where you’re confident that the asynchronous operation will always succeed.
It allows you to create an Effect
that represents successful completion without considering potential errors. However, it’s essential to ensure that the underlying Promise never rejects.
Example (Delayed Message)
1import { import Effect
Effect } from "effect"2
3const const delay: (message: string) => Effect.Effect<string, never, never>
delay = ((parameter) message: string
message: string) =>4 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<string>(5 () =>6 new var Promise: PromiseConstructor
new <string>(executor: (resolve: (value: string | PromiseLike<string>) => void, reject: (reason?: any) => void) => void) => Promise<string>
Creates a new Promise.
Promise(((parameter) resolve: (value: string | PromiseLike<string>) => void
resolve) => {7 function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)
namespace setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
setTimeout(() => {8 (parameter) resolve: (value: string | PromiseLike<string>) => void
resolve((parameter) message: string
message)9 }, 2000)10 })11 )12
13const const program: Effect.Effect<string, never, never>
program = const delay: (message: string) => Effect.Effect<string, never, never>
delay("Async operation completed successfully!")
The program
value has the type Effect<string, never, never>
and can be interpreted as an effect that:
- succeeds with a value of type
string
- does not produce any expected error (
never
) - does not require any context (
never
)
If, despite precautions, the thunk passed to Effect.promise
does reject, an Effect
containing a defect is created, similar to what happens when using the Effect.die function.
Unlike Effect.promise
, this constructor is suitable when the underlying Promise
might reject.
It provides a way to catch errors and handle them appropriately.
By default if an error occurs, it will be caught and propagated to the error channel as as an UnknownException
.
Example (Fetching a TODO Item)
1import { import Effect
Effect } from "effect"2
3const const getTodo: (id: number) => Effect.Effect<Response, UnknownException, never>
getTodo = ((parameter) id: number
id: number) =>4 import Effect
Effect.const tryPromise: <Response>(evaluate: (signal: AbortSignal) => PromiseLike<Response>) => Effect.Effect<Response, 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(() =>5 function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>
fetch(`https://jsonplaceholder.typicode.com/todos/${(parameter) id: number
id}`)6 )7
8const const program: Effect.Effect<Response, UnknownException, never>
program = const getTodo: (id: number) => Effect.Effect<Response, UnknownException, never>
getTodo(1)
The program
value has the type Effect<Response, UnknownException, never>
and can be interpreted as an effect that:
- succeeds with a value of type
Response
- might produce an error (
UnknownException
) - does not require any context (
never
)
If you want more control over what gets propagated to the error channel, you can use an overload of Effect.tryPromise
that takes a remapping function:
Example (Custom Error Handling)
1import { import Effect
Effect } from "effect"2
3const const getTodo: (id: number) => Effect.Effect<Response, Error, never>
getTodo = ((parameter) id: number
id: number) =>4 import Effect
Effect.const tryPromise: <Response, Error>(options: {
readonly try: (signal: AbortSignal) => PromiseLike<Response>;
readonly catch: (error: unknown) => Error;
}) => Effect.Effect<...> (+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({5 (property) try: (signal: AbortSignal) => PromiseLike<Response>
try: () => function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>
fetch(`https://jsonplaceholder.typicode.com/todos/${(parameter) id: number
id}`),6 // remap the error7 (property) catch: (error: unknown) => Error
catch: ((parameter) unknown: unknown
unknown) => new var Error: ErrorConstructor
new (message?: string) => Error
Error(`something went wrong ${(parameter) unknown: unknown
unknown}`)8 })9
10const const program: Effect.Effect<Response, Error, never>
program = const getTodo: (id: number) => Effect.Effect<Response, Error, never>
getTodo(1)
Sometimes you have to work with APIs that don’t support async/await
or Promise
and instead use the callback style.
To handle callback-based APIs, Effect provides the Effect.async
constructor.
Example (Wrapping a Callback API)
Let’s wrap the readFile
function from Node.js’s fs
module into an Effect-based API (make sure @types/node
is installed):
1import { import Effect
Effect } from "effect"2import * as (alias) module "node:fs"
import NodeFS
NodeFS from "node:fs"3
4const const readFile: (filename: string) => Effect.Effect<Buffer, Error, never>
readFile = ((parameter) filename: string
filename: string) =>5 import Effect
Effect.const async: <Buffer, Error, never>(resume: (callback: (_: Effect.Effect<Buffer, Error, never>) => void, signal: AbortSignal) => void | Effect.Effect<void, never, never>, blockingOn?: FiberId) => Effect.Effect<...>
Creates an `Effect` from a callback-based asynchronous API.
Useful for integrating Node.js-style callback functions into the Effect system.
The `resume` function **MUST** be called at most once.
The `resume` function can optionally return an `Effect`, which will be
executed if the `Fiber` executing this `Effect` is interrupted.
The `resume` function can also receive an `AbortSignal` if required for
interruption.
The `FiberId` of the fiber that may complete the async callback may also be
specified. This is called the "blocking fiber" because it suspends the fiber
executing the `async` effect (i.e. semantically blocks the fiber from making
progress). Specifying this fiber id in cases where it is known will improve
diagnostics, but not affect the behavior of the returned effect.
async<interface Buffer
Buffer, interface Error
Error>(((parameter) resume: (_: Effect.Effect<Buffer, Error, never>) => void
resume) => {6 (alias) module "node:fs"
import NodeFS
NodeFS.function readFile(path: NodeFS.PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void (+3 overloads)
namespace readFile
Asynchronously reads the entire contents of a file.
readFile((parameter) filename: string
filename, ((parameter) error: NodeJS.ErrnoException | null
error, (parameter) data: Buffer
data) => {7 if ((parameter) error: NodeJS.ErrnoException | null
error) {8 // Resume with a failed Effect if an error occurs9 (parameter) resume: (_: Effect.Effect<Buffer, Error, never>) => void
resume(import Effect
Effect.const fail: <NodeJS.ErrnoException>(error: NodeJS.ErrnoException) => Effect.Effect<never, NodeJS.ErrnoException, 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((parameter) error: NodeJS.ErrnoException
error))10 } else {11 // Resume with a succeeded Effect if successful12 (parameter) resume: (_: Effect.Effect<Buffer, Error, never>) => void
resume(import Effect
Effect.const succeed: <Buffer>(value: Buffer) => Effect.Effect<Buffer, 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) data: Buffer
data))13 }14 })15 })16
17// ┌─── Effect<Buffer, Error, never>18// ▼19const const program: Effect.Effect<Buffer, Error, never>
program = const readFile: (filename: string) => Effect.Effect<Buffer, Error, never>
readFile("example.txt")
In the above example, we manually annotate the types when calling Effect.async
:
Effect.async<Buffer, Error>((resume) => { // ...})
because TypeScript cannot infer the type parameters for a callback
based on the return value inside the callback body. Annotating the types ensures that the values provided to resume
match the expected types.
The resume
function inside Effect.async
should be called exactly once. Calling it more than once will result in the extra calls being ignored.
Example (Ignoring Subsequent resume
Calls)
1import { import Effect
Effect } from "effect"2
3const const program: Effect.Effect<number, never, never>
program = import Effect
Effect.const async: <number, never, never>(resume: (callback: (_: Effect.Effect<number, never, never>) => void, signal: AbortSignal) => void | Effect.Effect<void, never, never>, blockingOn?: FiberId) => Effect.Effect<...>
Creates an `Effect` from a callback-based asynchronous API.
Useful for integrating Node.js-style callback functions into the Effect system.
The `resume` function **MUST** be called at most once.
The `resume` function can optionally return an `Effect`, which will be
executed if the `Fiber` executing this `Effect` is interrupted.
The `resume` function can also receive an `AbortSignal` if required for
interruption.
The `FiberId` of the fiber that may complete the async callback may also be
specified. This is called the "blocking fiber" because it suspends the fiber
executing the `async` effect (i.e. semantically blocks the fiber from making
progress). Specifying this fiber id in cases where it is known will improve
diagnostics, but not affect the behavior of the returned effect.
async<number>(((parameter) resume: (_: Effect.Effect<number, never, never>) => void
resume) => {4 (parameter) resume: (_: Effect.Effect<number, never, never>) => void
resume(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(1))5 (parameter) resume: (_: Effect.Effect<number, never, never>) => void
resume(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(2)) // This line will be ignored6})7
8// Run the program9import 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 program: Effect.Effect<number, never, never>
program).(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: 1
For more advanced use cases, resume
can optionally return an Effect
that will be executed if the fiber running this effect is interrupted. This can be useful in scenarios where you need to handle resource cleanup if the operation is interrupted.
Example (Handling Interruption with Cleanup)
In this example:
- The
writeFileWithCleanup
function writes data to a file. - If the fiber running this effect is interrupted, the cleanup effect (which deletes the file) is executed.
- This ensures that resources like open file handles are cleaned up properly when the operation is canceled.
1import { Effect, Fiber } from "effect"2import * as NodeFS from "node:fs"3
4// Simulates a long-running operation to write to a file5const writeFileWithCleanup = (filename: string, data: string) =>6 Effect.async<void, Error>((resume) => {7 const writeStream = NodeFS.createWriteStream(filename)8
9 // Start writing data to the file10 writeStream.write(data)11
12 // When the stream is finished, resume with success13 writeStream.on("finish", () => resume(Effect.void))14
15 // In case of an error during writing, resume with failure16 writeStream.on("error", (err) => resume(Effect.fail(err)))17
18 // Handle interruption by returning a cleanup effect19 return Effect.sync(() => {20 console.log(`Cleaning up ${filename}`)21 NodeFS.unlinkSync(filename)22 })23 })24
25const program = Effect.gen(function* () {26 const fiber = yield* Effect.fork(27 writeFileWithCleanup("example.txt", "Some long data...")28 )29 // Simulate interrupting the fiber after 1 second30 yield* Effect.sleep("1 second")31 yield* Fiber.interrupt(fiber) // This will trigger the cleanup32})33
34// Run the program35Effect.runPromise(program)36/*37Output:38Cleaning up example.txt39*/
If the operation you’re wrapping supports interruption, the resume
function can receive an AbortSignal
to handle interruption requests directly.
Example (Handling Interruption with AbortSignal
)
1import { import Effect
Effect, import Fiber
Fiber } from "effect"2
3// A task that supports interruption using AbortSignal4const const interruptibleTask: Effect.Effect<void, Error, never>
interruptibleTask = import Effect
Effect.const async: <void, Error, never>(resume: (callback: (_: Effect.Effect<void, Error, never>) => void, signal: AbortSignal) => void | Effect.Effect<void, never, never>, blockingOn?: FiberId) => Effect.Effect<...>
Creates an `Effect` from a callback-based asynchronous API.
Useful for integrating Node.js-style callback functions into the Effect system.
The `resume` function **MUST** be called at most once.
The `resume` function can optionally return an `Effect`, which will be
executed if the `Fiber` executing this `Effect` is interrupted.
The `resume` function can also receive an `AbortSignal` if required for
interruption.
The `FiberId` of the fiber that may complete the async callback may also be
specified. This is called the "blocking fiber" because it suspends the fiber
executing the `async` effect (i.e. semantically blocks the fiber from making
progress). Specifying this fiber id in cases where it is known will improve
diagnostics, but not affect the behavior of the returned effect.
async<void, interface Error
Error>(((parameter) resume: (_: Effect.Effect<void, Error, never>) => void
resume, (parameter) signal: AbortSignal
signal) => {5 // Handle interruption6 (parameter) signal: AbortSignal
signal.(method) addEventListener(type: string, listener: EventListener | EventListenerObject, options?: AddEventListenerOptions | boolean): void
Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value.
If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched.
The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification.
Specifically, the `capture` option is used as part of the key when registering a `listener`.
Any individual `listener` may be added once with `capture = false`, and once with `capture = true`.
addEventListener("abort", () => {7 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("Abort signal received")8 function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void
Cancels a `Timeout` object created by `setTimeout()`.
clearTimeout(const timeoutId: NodeJS.Timeout
timeoutId)9 })10
11 // Simulate a long-running task12 const const timeoutId: NodeJS.Timeout
timeoutId = function setTimeout<[]>(callback: () => void, ms?: number): NodeJS.Timeout (+1 overload)
namespace setTimeout
Schedules execution of a one-time `callback` after `delay` milliseconds.
The `callback` will likely not be invoked in precisely `delay` milliseconds.
Node.js makes no guarantees about the exact timing of when callbacks will fire,
nor of their ordering. The callback will be called as close as possible to the
time specified.
When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer.
If `callback` is not a function, a `TypeError` will be thrown.
This method has a custom variant for promises that is available using `timersPromises.setTimeout()`.
setTimeout(() => {13 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("Operation completed")14 (parameter) resume: (_: Effect.Effect<void, Error, never>) => void
resume(import Effect
Effect.(alias) const void: Effect.Effect<void, never, never>
export void
void)15 }, 2000)16})17
18const const program: Effect.Effect<void, never, never>
program = import Effect
Effect.const gen: <YieldWrap<Effect.Effect<void, never, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<void, never, never>>, void, never>) => Effect.Effect<...> (+1 overload)
gen(function* () {19 const const fiber: Fiber.RuntimeFiber<void, Error>
fiber = yield* import Effect
Effect.const fork: <void, Error, never>(self: Effect.Effect<void, Error, never>) => Effect.Effect<Fiber.RuntimeFiber<void, Error>, never, never>
Returns an effect that forks this effect into its own separate fiber,
returning the fiber immediately, without waiting for it to begin executing
the effect.
You can use the `fork` method whenever you want to execute an effect in a
new fiber, concurrently and without "blocking" the fiber executing other
effects. Using fibers can be tricky, so instead of using this method
directly, consider other higher-level methods, such as `raceWith`,
`zipPar`, and so forth.
The fiber returned by this method has methods to interrupt the fiber and to
wait for it to finish executing the effect. See `Fiber` for more
information.
Whenever you use this method to launch a new fiber, the new fiber is
attached to the parent fiber's scope. This means when the parent fiber
terminates, the child fiber will be terminated as well, ensuring that no
fibers leak. This behavior is called "auto supervision", and if this
behavior is not desired, you may use the `forkDaemon` or `forkIn` methods.
fork(const interruptibleTask: Effect.Effect<void, Error, never>
interruptibleTask)20 // Simulate interrupting the fiber after 1 second21 yield* import Effect
Effect.const sleep: (duration: DurationInput) => Effect.Effect<void>
Returns an effect that suspends for the specified duration. This method is
asynchronous, and does not actually block the fiber executing the effect.
sleep("1 second")22 yield* import Fiber
Fiber.const interrupt: <void, Error>(self: Fiber.Fiber<void, Error>) => Effect.Effect<Exit<void, Error>, never, never>
Interrupts the fiber from whichever fiber is calling this method. If the
fiber has already exited, the returned effect will resume immediately.
Otherwise, the effect will resume when the fiber exits.
interrupt(const fiber: Fiber.RuntimeFiber<void, Error>
fiber)23})24
25// Run the program26import Effect
Effect.const runPromise: <void, never>(effect: Effect.Effect<void, never, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<void>
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<void, never, never>
program)27/*28Output:29Abort signal received30*/
Effect.suspend
is used to delay the creation of an effect.
It allows you to defer the evaluation of an effect until it is actually needed.
The Effect.suspend
function takes a thunk that represents the effect, and it wraps it in a suspended effect.
Syntax
const suspendedEffect = Effect.suspend(() => effect)
Let’s explore some common scenarios where Effect.suspend
proves useful.
When you want to defer the evaluation of an effect until it is required. This can be useful for optimizing the execution of effects, especially when they are not always needed or when their computation is expensive.
Also, when effects with side effects or scoped captures are created, use Effect.suspend
to re-execute on each invocation.
Example (Lazy Evaluation with Side Effects)
1import { import Effect
Effect } from "effect"2
3let let i: number
i = 04
5const const bad: Effect.Effect<number, never, never>
bad = 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(let i: number
i++)6
7const const good: Effect.Effect<number, never, never>
good = import Effect
Effect.const suspend: <number, never, never>(effect: LazyArg<Effect.Effect<number, never, never>>) => Effect.Effect<number, never, never>
Creates an `Effect` that defers the creation of another effect until it is needed.
Useful for lazy evaluation, handling circular dependencies, or avoiding eager execution in recursive functions.
suspend(() => 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(let i: number
i++))8
9namespace 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(import Effect
Effect.const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
Executes an effect synchronously and returns its result.
Use `runSync` when you are certain that the effect is purely synchronous and will not perform any asynchronous operations.
If the effect fails or contains asynchronous tasks, it will throw an error.
runSync(const bad: Effect.Effect<number, never, never>
bad)) // Output: 010namespace 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(import Effect
Effect.const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
Executes an effect synchronously and returns its result.
Use `runSync` when you are certain that the effect is purely synchronous and will not perform any asynchronous operations.
If the effect fails or contains asynchronous tasks, it will throw an error.
runSync(const bad: Effect.Effect<number, never, never>
bad)) // Output: 011
12namespace 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(import Effect
Effect.const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
Executes an effect synchronously and returns its result.
Use `runSync` when you are certain that the effect is purely synchronous and will not perform any asynchronous operations.
If the effect fails or contains asynchronous tasks, it will throw an error.
runSync(const good: Effect.Effect<number, never, never>
good)) // Output: 113namespace 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(import Effect
Effect.const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
Executes an effect synchronously and returns its result.
Use `runSync` when you are certain that the effect is purely synchronous and will not perform any asynchronous operations.
If the effect fails or contains asynchronous tasks, it will throw an error.
runSync(const good: Effect.Effect<number, never, never>
good)) // Output: 2
In this example, bad
is the result of calling Effect.succeed(i++)
a single time, which increments the scoped variable but returns its original value. Effect.runSync(bad)
does not result in any new computation, because Effect.succeed(i++)
has already been called. On the other hand, each time Effect.runSync(good)
is called, the thunk passed to Effect.suspend()
will be executed, outputting the scoped variable’s most recent value.
Effect.suspend
is helpful in managing circular dependencies between effects, where one effect depends on another, and vice versa.
For example it’s fairly common for Effect.suspend
to be used in recursive functions to escape an eager call.
Example (Recursive Fibonacci)
1import { import Effect
Effect } from "effect"2
3const const blowsUp: (n: number) => Effect.Effect<number>
blowsUp = ((parameter) n: number
n: number): 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> =>4 (parameter) n: number
n < 25 ? 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(1)6 : import Effect
Effect.const zipWith: <number, never, never, number, never, never, number>(self: Effect.Effect<number, never, never>, that: Effect.Effect<number, never, never>, f: (a: number, b: number) => number, options?: {
readonly concurrent?: boolean | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}) => Effect.Effect<...> (+1 overload)
The `Effect.zipWith` function operates similarly to
{@link
zip
}
by combining
two effects. However, instead of returning a tuple, it allows you to apply a
function to the results of the combined effects, transforming them into a
single value
zipWith(const blowsUp: (n: number) => Effect.Effect<number>
blowsUp((parameter) n: number
n - 1), const blowsUp: (n: number) => Effect.Effect<number>
blowsUp((parameter) n: number
n - 2), ((parameter) a: number
a, (parameter) b: number
b) => (parameter) a: number
a + (parameter) b: number
b)7
8// console.log(Effect.runSync(blowsUp(32)))9// crash: JavaScript heap out of memory10
11const const allGood: (n: number) => Effect.Effect<number>
allGood = ((parameter) n: number
n: number): 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> =>12 (parameter) n: number
n < 213 ? 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(1)14 : import Effect
Effect.const zipWith: <number, never, never, number, never, never, number>(self: Effect.Effect<number, never, never>, that: Effect.Effect<number, never, never>, f: (a: number, b: number) => number, options?: {
readonly concurrent?: boolean | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}) => Effect.Effect<...> (+1 overload)
The `Effect.zipWith` function operates similarly to
{@link
zip
}
by combining
two effects. However, instead of returning a tuple, it allows you to apply a
function to the results of the combined effects, transforming them into a
single value
zipWith(15 import Effect
Effect.const suspend: <number, never, never>(effect: LazyArg<Effect.Effect<number, never, never>>) => Effect.Effect<number, never, never>
Creates an `Effect` that defers the creation of another effect until it is needed.
Useful for lazy evaluation, handling circular dependencies, or avoiding eager execution in recursive functions.
suspend(() => const allGood: (n: number) => Effect.Effect<number>
allGood((parameter) n: number
n - 1)),16 import Effect
Effect.const suspend: <number, never, never>(effect: LazyArg<Effect.Effect<number, never, never>>) => Effect.Effect<number, never, never>
Creates an `Effect` that defers the creation of another effect until it is needed.
Useful for lazy evaluation, handling circular dependencies, or avoiding eager execution in recursive functions.
suspend(() => const allGood: (n: number) => Effect.Effect<number>
allGood((parameter) n: number
n - 2)),17 ((parameter) a: number
a, (parameter) b: number
b) => (parameter) a: number
a + (parameter) b: number
b18 )19
20namespace 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(import Effect
Effect.const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
Executes an effect synchronously and returns its result.
Use `runSync` when you are certain that the effect is purely synchronous and will not perform any asynchronous operations.
If the effect fails or contains asynchronous tasks, it will throw an error.
runSync(const allGood: (n: number) => Effect.Effect<number>
allGood(32))) // Output: 3524578
The blowsUp
function creates a recursive Fibonacci sequence without deferring execution. Each call to blowsUp
triggers further immediate recursive calls, rapidly increasing the JavaScript call stack size.
Conversely, allGood
avoids stack overflow by using Effect.suspend
to defer the recursive calls. This mechanism doesn’t immediately execute the recursive effects but schedules them to be run later, thus keeping the call stack shallow and preventing a crash.
In situations where TypeScript struggles to unify the returned effect type, Effect.suspend
can be employed to resolve this issue.
Example
1import { import Effect
Effect } from "effect"2
3const const ugly: (a: number, b: number) => Effect.Effect<never, Error, never> | Effect.Effect<number, never, never>
ugly = ((parameter) a: number
a: number, (parameter) b: number
b: number) =>4 (parameter) b: number
b === 05 ? 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("Cannot divide by zero"))6 : 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) a: number
a / (parameter) b: number
b)7
8const const nice: (a: number, b: number) => Effect.Effect<number, Error, never>
nice = ((parameter) a: number
a: number, (parameter) b: number
b: number) =>9 import Effect
Effect.const suspend: <number, Error, never>(effect: LazyArg<Effect.Effect<number, Error, never>>) => Effect.Effect<number, Error, never>
Creates an `Effect` that defers the creation of another effect until it is needed.
Useful for lazy evaluation, handling circular dependencies, or avoiding eager execution in recursive functions.
suspend(() =>10 (parameter) b: number
b === 011 ? 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("Cannot divide by zero"))12 : 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) a: number
a / (parameter) b: number
b)13 )
The table provides a summary of the available constructors, along with their input and output types, allowing you to choose the appropriate function based on your needs.
API | Given | Result |
---|---|---|
succeed | A | Effect<A> |
fail | E | Effect<never, E> |
sync | () => A | Effect<A> |
try | () => A | Effect<A, UnknownException> |
try (overload) | () => A , unknown => E | Effect<A, E> |
promise | () => Promise<A> | Effect<A> |
tryPromise | () => Promise<A> | Effect<A, UnknownException> |
tryPromise (overload) | () => Promise<A> , unknown => E | Effect<A, E> |
async | (Effect<A, E> => void) => void | Effect<A, E> |
suspend | () => Effect<A, E, R> | Effect<A, E, R> |
For the complete list of constructors, visit the Effect Constructors Documentation.