Skip to content

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:

1
const
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
b
6
}

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 in the Effect library is used to explicitly create an effect that is guaranteed to succeed. Here’s how you can use it:

1
import {
import Effect
Effect
} from "effect"
2
3
// Creating an effect that represents a successful scenario
4
const
const success: Effect.Effect<number, never, never>
success
=
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>
succeed
(42)

In this example, success is an instance of Effect<number, never, never>. This means it’s an effect that:

  • Always succeeds, yielding a value of type number.
  • Does not generate any errors (never indicates that no errors are expected).
  • Requires no additional data or dependencies from the environment (never indicates no requirements).

When a computation might fail, it’s essential to manage the failure explicitly. The Effect.fail constructor allows you to encapsulate an error within your program flow explicitly. This method is useful for representing known error states in a predictable and type-safe way. Here’s a practical example to illustrate:

1
import {
import Effect
Effect
} from "effect"
2
3
// Creating an effect that represents a failure scenario
4
const
const failure: Effect.Effect<never, Error, never>
failure
=
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>
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 successful value (never).
  • It fails with an error, specifically an Error.
  • It does not depend on any external context to execute (never).

While you can use Error objects with Effect.fail, it also supports strings, numbers, or more complex objects, depending on your error management strategy.

However, using “tagged” errors, which are objects with a _tag field, helps identify error types and integrates well with standard Effect functions like Effect.catchTag.

1
import {
import Effect
Effect
} from "effect"
2
3
class
class NetworkError
NetworkError
{
4
readonly
(property) NetworkError._tag: "NetworkError"
_tag
= "NetworkError"
5
}
6
7
const
const failure: Effect.Effect<never, NetworkError, never>
failure
=
import Effect
Effect
.
const fail: <NetworkError>(error: NetworkError) => Effect.Effect<never, NetworkError, never>
fail
(new
constructor NetworkError(): NetworkError
NetworkError
())

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)

Let’s see an example of rewriting the divide function using Effect to make the error handling explicit:

1
import {
import Effect
Effect
} from "effect"
2
3
const
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
=== 0
5
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>
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>
succeed
(
(parameter) a: number
a
/
(parameter) b: number
b
)

In this example, the divide function explicitly indicates that it can produce an effect that either fails with an Error or succeeds with a number value.

The type signature makes it clear how errors are handled and ensures that callers are 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:

1
import {
import Effect
Effect
} from "effect"
2
3
// Define a User type
4
interface
interface User
User
{
5
readonly
(property) User.id: number
id
: number
6
readonly
(property) User.name: string
name
: string
7
}
8
9
// A mocked function to simulate fetching a user from a database
10
const
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 it
12
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 appropriately
18
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>
succeed
(
const user: User
user
)
21
} else {
22
return
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>
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 1
27
const
const exampleUserEffect: Effect.Effect<User, Error, never>
exampleUserEffect
=
const getUser: (userId: number) => Effect.Effect<User, Error>
getUser
(1)

In this example exampleUserEffect can result in either a User object or an Error, depending on whether the user exists in the simulated database

To dive deeper into handling and managing errors effectively in your applications using Effect, you might want to explore the guide on Error Management. This guide provides detailed insights and strategies for robust error handling in TypeScript applications using Effect.

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)

1
import {
import Effect
Effect
} from "effect"
2
3
const
const log: (message: string) => Effect.Effect<void, never, never>
log
= (
(parameter) message: string
message
: string) =>
4
import Effect
Effect
.
const sync: <void>(evaluate: LazyArg<void>) => Effect.Effect<void, never, never>
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 effect
6
})
7
8
const
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.

The program has the type Effect<void, never, never>, indicating that:

  • It doesn’t produce a return value (void).
  • It’s not expected to fail (never indicates no expected errors).
  • It doesn’t require any external dependencies or context (never).

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:

1
import {
import Effect
Effect
} from "effect"
2
3
const
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 JSON
5
import Effect
Effect
.
(alias) try<any>(evaluate: 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
7
const
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 by program will fail with an UnknownException. This ensures that errors are not silently ignored but are instead handled within the structured flow of effects.

Customizing Error Handling. 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)

1
import { Effect } from "effect"
2
3
const parse = (input: string) =>
4
Effect.try({
5
// JSON.parse may throw for bad input
6
try: () => JSON.parse(input),
7
// remap the error
8
catch: (unknown) => new Error(`something went wrong ${unknown}`)
9
})
10
11
const 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 Promises 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)

1
import {
import Effect
Effect
} from "effect"
2
3
const
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>

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

Handling Unexpected Errors. 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)

1
import {
import Effect
Effect
} from "effect"
2
3
const
const getTodo: (id: number) => Effect.Effect<Response, UnknownException, never>
getTodo
= (
(parameter) id: number
id
: number) =>
4
import Effect
Effect
.
const tryPromise: <Response>(try_: (signal: AbortSignal) => PromiseLike<Response>) => Effect.Effect<Response, UnknownException, never> (+1 overload)

Create an `Effect` that when executed will construct `promise` and wait for its result, errors will produce failure as `unknown`. An optional `AbortSignal` can be provided to allow for interruption of the wrapped Promise api.

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

Customizing Error Handling. 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:

1
import { Effect } from "effect"
2
3
const getTodo = (id: number) =>
4
Effect.tryPromise({
5
try: () => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`),
6
// remap the error
7
catch: (unknown) => new Error(`something went wrong ${unknown}`)
8
})
9
10
const program = 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 (Reading a File)

For example, let’s wrap the readFile async API from the Node.js fs module with Effect (ensure you have @types/node installed):

1
import {
import Effect
Effect
} from "effect"
2
import * as
(alias) module "node:fs" import NodeFS
NodeFS
from "node:fs"
3
4
const
const readFile: (filename: string) => Effect.Effect<Buffer, Error, never>
readFile
= (
(parameter) filename: string
filename
: string) =>
5
import Effect
Effect
.
const async: <Buffer, Error, never>(register: (callback: (_: Effect.Effect<Buffer, Error, never>) => void, signal: AbortSignal) => void | Effect.Effect<void, never, never>, blockingOn?: FiberId) => Effect.Effect<...>

Imports an asynchronous side-effect into a pure `Effect` value. The callback function `Effect<A, E, R> => void` **MUST** be called at most once. The registration function can optionally return an Effect, which will be executed if the `Fiber` executing this Effect is interrupted. The registration function can also receive an `AbortSignal` if required for interruption. The `FiberId` of the fiber that may complete the async callback may also be specified. This is called the "blocking fiber" because it suspends the fiber executing the `async` Effect (i.e. semantically blocks the fiber from making progress). Specifying this fiber id in cases where it is known will improve diagnostics, but not affect the behavior of the returned effect.

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
(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>
fail
(
(parameter) error: NodeJS.ErrnoException
error
))
9
} else {
10
(parameter) resume: (_: Effect.Effect<Buffer, Error, never>) => void
resume
(
import Effect
Effect
.
const succeed: <Buffer>(value: Buffer) => Effect.Effect<Buffer, never, never>
succeed
(
(parameter) data: Buffer
data
))
11
}
12
})
13
})
14
15
const
const program: Effect.Effect<Buffer, Error, never>
program
=
const readFile: (filename: string) => Effect.Effect<Buffer, Error, never>
readFile
("todos.txt")

In the above example, we manually annotate the types when calling Effect.async 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.

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.

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.

1
import {
import Effect
Effect
} from "effect"
2
3
let
let i: number
i
= 0
4
5
const
const bad: Effect.Effect<number, never, never>
bad
=
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>
succeed
(
let i: number
i
++)
6
7
const
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>
suspend
(() =>
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>
succeed
(
let i: number
i
++))
8
9
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
(
import Effect
Effect
.
const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
runSync
(
const bad: Effect.Effect<number, never, never>
bad
)) // Output: 0
10
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
(
import Effect
Effect
.
const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
runSync
(
const bad: Effect.Effect<number, never, never>
bad
)) // Output: 0
11
12
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
(
import Effect
Effect
.
const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
runSync
(
const good: Effect.Effect<number, never, never>
good
)) // Output: 1
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
(
import Effect
Effect
.
const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
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. For instance:

1
import {
import Effect
Effect
} from "effect"
2
3
const
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
< 2
5
?
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>
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 memory
10
11
const
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
< 2
13
?
import Effect
Effect
.
const succeed: <number>(value: number) => Effect.Effect<number, never, never>
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>
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>
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
b
18
)
19
20
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
(
import Effect
Effect
.
const runSync: <number, never>(effect: Effect.Effect<number, never, never>) => number
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. For example:

1
import {
import Effect
Effect
} from "effect"
2
3
const
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
=== 0
5
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>
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>
succeed
(
(parameter) a: number
a
/
(parameter) b: number
b
)
7
8
const
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>
suspend
(() =>
10
(parameter) b: number
b
=== 0
11
?
import Effect
Effect
.
const fail: <Error>(error: Error) => Effect.Effect<never, Error, never>
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>
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.

APIGivenTo
succeedAEffect<A>
failEEffect<never, E>
sync() => AEffect<A>
try() => AEffect<A, UnknownException>
try (overload)() => A, unknown => EEffect<A, E>
promise() => Promise<A>Effect<A>
tryPromise() => Promise<A>Effect<A, UnknownException>
tryPromise (overload)() => Promise<A>, unknown => EEffect<A, E>
async(Effect<A, E> => void) => voidEffect<A, E>
suspend() => Effect<A, E, R>Effect<A, E, R>

You can find the complete list of constructors here.

Now that we know how to create effects, it’s time to learn how to run them. Check out the next guide on Running Effects to find out more.