Option
The Option
data type is used to represent optional values. An Option
can be either Some
, which contains a value, or None
, which indicates the absence of a value.
The Option
type is versatile and can be applied in various scenarios, including:
- Using it for initial values
- Returning values from functions that are not defined for all possible inputs (referred to as “partial functions”)
- Managing optional fields in data structures
- Handling optional function arguments
The Option.some
constructor takes a value of type A
and returns an Option<A>
that holds that value:
1import { import Option
Option } from "effect"2
3const const value: Option.Option<number>
value = import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(1) // An Option holding the number 1
On the other hand, the Option.none
constructor returns an Option<never>
, representing the absence of a value:
1import { import Option
Option } from "effect"2
3const const noValue: Option.Option<never>
noValue = import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none() // An Option holding no value
Sometimes you need to create an Option
based on a predicate, such as checking if a value is positive.
Here’s how you can do this explicitly using Option.none
and Option.some
1import { import Option
Option } from "effect"2
3const const isPositive: (n: number) => boolean
isPositive = ((parameter) n: number
n: number) => (parameter) n: number
n > 04
5const const parsePositive: (n: number) => Option.Option<number>
parsePositive = ((parameter) n: number
n: number): import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number> =>6 const isPositive: (n: number) => boolean
isPositive((parameter) n: number
n) ? import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some((parameter) n: number
n) : import Option
Option.const none: <number>() => Option.Option<number>
Creates a new `Option` that represents the absence of a value.
none()
The same result can be achieved more concisely using Option.liftPredicate
1import { import Option
Option } from "effect"2
3const const isPositive: (n: number) => boolean
isPositive = ((parameter) n: number
n: number) => (parameter) n: number
n > 04
5const const parsePositive: (b: number) => Option.Option<number>
parsePositive = import Option
Option.const liftPredicate: <number, number>(predicate: Predicate<number>) => (b: number) => Option.Option<number> (+3 overloads)
Transforms a `Predicate` function into a `Some` of the input value if the predicate returns `true` or `None`
if the predicate returns `false`.
liftPredicate(const isPositive: (n: number) => boolean
isPositive)
Let’s look at an example of a User
model where the "email"
property is optional and can have a value of type string
.
To represent this, we can use the Option<string>
type:
1import { import Option
Option } from "effect"2
3interface interface User
User {4 readonly (property) User.id: number
id: number5 readonly (property) User.username: string
username: string6 readonly (property) User.email: Option.Option<string>
email: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string>7}
Now, let’s see how we can create instances of User
with and without an email:
1importconst withEmail: User
{ Option } from "effect"23interface User {4 (property) User.email: Option.Option<string>
readonly id: nconst some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
umber5 readonly username: string6 readonly email: Option.Option<string>7}89//(property) User.username: string
---cut---10const witimport Option
hEmail: User = {11 id: 1,12 username: "john_doe",13 email: Option.some("john.doe@example.com")14}15
16const withoutEmail: User = {17 id: 2,18 username: "jane_doe",19 email: Option.none()20}
You can determine whether an Option
is a Some
or a None
by using the isSome
and isNone
guards:
1import { import Option
Option } from "effect"2
3const const foo: Option.Option<number>
foo = import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(1)4
5namespace 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 Option
Option.const isSome: <number>(self: Option.Option<number>) => self is Option.Some<number>
Determine if a `Option` is a `Some`.
isSome(const foo: Option.Option<number>
foo)) // Output: true6
7if (import Option
Option.const isNone: <number>(self: Option.Option<number>) => self is Option.None<number>
Determine if a `Option` is a `None`.
isNone(const foo: Option.Option<number>
foo)) {8 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("Option is empty")9} else {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(`Option has a value: ${const foo: Option.Some<number>
foo.(property) Some<number>.value: number
value}`)11}12// Output: "Option has a value: 1"
The Option.match
function allows you to handle different cases of an Option
value by providing separate actions for each case:
1import { import Option
Option } from "effect"2
3const const foo: Option.Option<number>
foo = import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(1)4
5const const result: string
result = import Option
Option.const match: <number, string, string>(self: Option.Option<number>, options: {
readonly onNone: LazyArg<string>;
readonly onSome: (a: number) => string;
}) => string (+1 overload)
Matches the given `Option` and returns either the provided `onNone` value or the result of the provided `onSome`
function when passed the `Option`'s value.
match(const foo: Option.Option<number>
foo, {6 (property) onNone: LazyArg<string>
onNone: () => "Option is empty",7 (property) onSome: (a: number) => string
onSome: ((parameter) value: number
value) => `Option has a value: ${(parameter) value: number
value}`8})9
10namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(const result: string
result) // Output: "Option has a value: 1"
The Option.map
function allows you to transform the value inside an Option
without having to unwrap and wrap the underlying value. Let’s see an example:
1import { import Option
Option } from "effect"2
3const const maybeIncremented: Option.Option<number>
maybeIncremented = import Option
Option.const map: <number, number>(self: Option.Option<number>, f: (a: number) => number) => Option.Option<number> (+1 overload)
Maps the `Some` side of an `Option` value to a new `Option` value.
map(import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(1), ((parameter) n: number
n) => (parameter) n: number
n + 1) // some(2)
The convenient aspect of using Option
is how it handles the absence of a value, represented by None
:
1import { import Option
Option } from "effect"2
3const const maybeIncremented: Option.Option<number>
maybeIncremented = import Option
Option.const map: <never, number>(self: Option.Option<never>, f: (a: never) => number) => Option.Option<number> (+1 overload)
Maps the `Some` side of an `Option` value to a new `Option` value.
map(import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none(), ((parameter) n: never
n) => (parameter) n: never
n + 1) // none()
Despite having None
as the input, we can still operate on the Option
without encountering errors. The mapping function (n) => n + 1
is not executed when the Option
is None
, and the result remains none
representing the absence of a value.
The Option.flatMap
function works similarly to Option.map
, but with an additional feature. It allows us to sequence computations that depend on the absence or presence of a value in an Option
.
Let’s explore an example that involves a nested optional property. We have a User
model with an optional address
field of type Option<Address>
:
1import { import Option
Option } from "effect"2
3interface interface User
User {4 readonly (property) User.id: number
id: number5 readonly (property) User.username: string
username: string6 readonly (property) User.email: Option.Option<string>
email: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string>7 readonly (property) User.address: Option.Option<Address>
address: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<interface Address
Address>8}9
10interface interface Address
Address {11 readonly (property) Address.city: string
city: string12 readonly (property) Address.street: Option.Option<string>
street: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string>13}
The address
field itself contains a nested optional property called street
of type Option<string>
:
1import { import Option
Option } from "effect"2
3interface interface User
User {4 readonly (property) User.id: number
id: number5 readonly (property) User.username: string
username: string6 readonly (property) User.email: Option.Option<string>
email: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string>7 readonly (property) User.address: Option.Option<Address>
address: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<interface Address
Address>8}9
10interface interface Address
Address {11 readonly (property) Address.city: string
city: string12 readonly (property) Address.street: Option.Option<string>
street: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string>13}
We can use Option.flatMap
to extract the street
property from the address
field.
1import { import Option
Option } from "effect"2
3interface interface Address
Address {4 readonly (property) Address.city: string
city: string5 readonly (property) Address.street: Option.Option<string>
street: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string>6}7
8interface interface User
User {9 readonly (property) User.id: number
id: number10 readonly (property) User.username: string
username: string11 readonly (property) User.email: Option.Option<string>
email: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string>12 readonly (property) User.address: Option.Option<Address>
address: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<interface Address
Address>13}14
15const const user: User
user: interface User
User = {16 (property) User.id: number
id: 1,17 (property) User.username: string
username: "john_doe",18 (property) User.email: Option.Option<string>
email: import Option
Option.const some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
some("john.doe@example.com"),19 (property) User.address: Option.Option<Address>
address: import Option
Option.const some: <{
city: string;
street: Option.Option<string>;
}>(value: {
city: string;
street: Option.Option<string>;
}) => Option.Option<{
city: string;
street: Option.Option<string>;
}>
Creates a new `Option` that wraps the given value.
some({20 (property) city: string
city: "New York",21 (property) street: Option.Option<string>
street: import Option
Option.const some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
some("123 Main St")22 })23}24
25const const street: Option.Option<string>
street = const user: User
user.(property) User.address: Option.Option<Address>
address.(method) Pipeable.pipe<Option.Option<Address>, Option.Option<string>>(this: Option.Option<Address>, ab: (_: Option.Option<Address>) => Option.Option<string>): Option.Option<...> (+21 overloads)
pipe(26 import Option
Option.const flatMap: <Address, string>(f: (a: Address) => Option.Option<string>) => (self: Option.Option<Address>) => Option.Option<string> (+1 overload)
Applies a function to the value of an `Option` and flattens the result, if the input is `Some`.
flatMap(((parameter) address: Address
address) => (parameter) address: Address
address.(property) Address.street: Option.Option<string>
street)27)
Here’s how it works: if the address
is Some
, meaning it has a value, the mapping function (addr) => addr.street
is applied to retrieve the street
value. On the other hand, if the address
is None
, indicating the absence of a value, the mapping function is not executed, and the result is also None
.
The Option.filter
function is used to filter an Option
using a predicate. If the predicate is not satisfied or the Option
is None
, it returns None
.
Let’s see an example where we refactor some code to a more idiomatic version:
Original Code
1import { import Option
Option } from "effect"2
3const const removeEmptyString: (input: Option.Option<string>) => Option.None<string> | Option.Some<string>
removeEmptyString = ((parameter) input: Option.Option<string>
input: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string>) => {4 if (import Option
Option.const isSome: <string>(self: Option.Option<string>) => self is Option.Some<string>
Determine if a `Option` is a `Some`.
isSome((parameter) input: Option.Option<string>
input) && (parameter) input: Option.Some<string>
input.(property) Some<string>.value: string
value === "") {5 return import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none()6 }7 return (parameter) input: Option.Option<string>
input8}9
10namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(const removeEmptyString: (input: Option.Option<string>) => Option.None<string> | Option.Some<string>
removeEmptyString(import Option
Option.const none: <string>() => Option.Option<string>
Creates a new `Option` that represents the absence of a value.
none())) // { _id: 'Option', _tag: 'None' }11namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(const removeEmptyString: (input: Option.Option<string>) => Option.None<string> | Option.Some<string>
removeEmptyString(import Option
Option.const some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
some(""))) // { _id: 'Option', _tag: 'None' }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(const removeEmptyString: (input: Option.Option<string>) => Option.None<string> | Option.Some<string>
removeEmptyString(import Option
Option.const some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
some("a"))) // { _id: 'Option', _tag: 'Some', value: 'a' }
Idiomatic Code
1import { import Option
Option } from "effect"2
3const const removeEmptyString: (input: Option.Option<string>) => Option.Option<string>
removeEmptyString = ((parameter) input: Option.Option<string>
input: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string>) =>4 import Option
Option.const filter: <string>(self: Option.Option<string>, predicate: Predicate<string>) => Option.Option<string> (+3 overloads)
Filters an `Option` using a predicate. If the predicate is not satisfied or the `Option` is `None` returns `None`.
If you need to change the type of the `Option` in addition to filtering, see `filterMap`.
filter((parameter) input: Option.Option<string>
input, ((parameter) value: string
value) => (parameter) value: string
value !== "")
To retrieve the value stored within an Option
, you can use various functions provided by the Option
module. Let’s explore these functions:
-
getOrThrow
: It retrieves the wrapped value from anOption
, or throws an error if theOption
is aNone
. Here’s an example:1import {Option } from "effect"import Option
23Option.import Option
getOrThrow(const getOrThrow: <number>(self: Option.Option<number>) => number
Extracts the value of an `Option` or throws if the `Option` is `None`. The thrown error is a default error. To configure the error thrown, see {@link getOrThrowWith } .
Option.import Option
some(10)) // 10const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
4Option.import Option
getOrThrow(const getOrThrow: <never>(self: Option.Option<never>) => never
Extracts the value of an `Option` or throws if the `Option` is `None`. The thrown error is a default error. To configure the error thrown, see {@link getOrThrowWith } .
Option.import Option
none()) // throws getOrThrow called on a Noneconst none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
-
getOrNull
andgetOrUndefined
: These functions are useful when you want to work with code that doesn’t useOption
. They allow you to retrieve the value of anOption
asnull
orundefined
, respectively. Examples:1import {Option } from "effect"import Option
23Option.import Option
getOrNull(const getOrNull: <number>(self: Option.Option<number>) => number | null
Returns the value of the `Option` if it is a `Some`, otherwise returns `null`.
Option.import Option
some(5)) // 5const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
4Option.import Option
getOrNull(const getOrNull: <never>(self: Option.Option<never>) => null
Returns the value of the `Option` if it is a `Some`, otherwise returns `null`.
Option.import Option
none()) // nullconst none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
56Option.import Option
getOrUndefined(const getOrUndefined: <number>(self: Option.Option<number>) => number | undefined
Returns the value of the `Option` if it is a `Some`, otherwise returns `undefined`.
Option.import Option
some(5)) // 5const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
7Option.import Option
getOrUndefined(const getOrUndefined: <never>(self: Option.Option<never>) => undefined
Returns the value of the `Option` if it is a `Some`, otherwise returns `undefined`.
Option.import Option
none()) // undefinedconst none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
-
getOrElse
: This function lets you provide a default value that will be returned if theOption
is aNone
. Here’s an example:1import {Option } from "effect"import Option
23Option.import Option
getOrElse(const getOrElse: <number, number>(self: Option.Option<number>, onNone: LazyArg<number>) => number (+1 overload)
Returns the value of the `Option` if it is `Some`, otherwise returns `onNone`
Option.import Option
some(5), () => 0) // 5const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
4Option.import Option
getOrElse(const getOrElse: <never, number>(self: Option.Option<never>, onNone: LazyArg<number>) => number (+1 overload)
Returns the value of the `Option` if it is `Some`, otherwise returns `onNone`
Option.import Option
none(), () => 0) // 0const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
In certain situations, when a computation returns None
, you may want to try an alternative computation that returns an Option
. This is where the Option.orElse
function comes in handy. It allows you to chain multiple computations together and continue with the next one if the previous one resulted in None
. This can be useful for implementing retry logic, where you want to attempt a computation multiple times until you either succeed or exhaust all possible attempts.
1import { import Option
Option } from "effect"2
3// Simulating a computation that may or may not produce a result4const const performComputation: () => Option.Option<number>
performComputation = (): import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number> =>5 var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.(method) Math.random(): number
Returns a pseudorandom number between 0 and 1.
random() < 0.5 ? import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(10) : import Option
Option.const none: <number>() => Option.Option<number>
Creates a new `Option` that represents the absence of a value.
none()6
7const const performAlternativeComputation: () => Option.Option<number>
performAlternativeComputation = (): import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number> =>8 var Math: Math
An intrinsic object that provides basic mathematics functionality and constants.
Math.(method) Math.random(): number
Returns a pseudorandom number between 0 and 1.
random() < 0.5 ? import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(20) : import Option
Option.const none: <number>() => Option.Option<number>
Creates a new `Option` that represents the absence of a value.
none()9
10const const result: Option.Option<number>
result = const performComputation: () => Option.Option<number>
performComputation().(method) Pipeable.pipe<Option.Option<number>, Option.Option<number>>(this: Option.Option<number>, ab: (_: Option.Option<number>) => Option.Option<number>): Option.Option<...> (+21 overloads)
pipe(11 import Option
Option.const orElse: <number>(that: LazyArg<Option.Option<number>>) => <A>(self: Option.Option<A>) => Option.Option<number | A> (+1 overload)
Returns the provided `Option` `that` if `self` is `None`, otherwise returns `self`.
orElse(() => const performAlternativeComputation: () => Option.Option<number>
performAlternativeComputation())12)13
14import Option
Option.const match: <number, void, void>(self: Option.Option<number>, options: {
readonly onNone: LazyArg<void>;
readonly onSome: (a: number) => void;
}) => void (+1 overload)
Matches the given `Option` and returns either the provided `onNone` value or the result of the provided `onSome`
function when passed the `Option`'s value.
match(const result: Option.Option<number>
result, {15 (property) onNone: LazyArg<void>
onNone: () => 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("Both computations resulted in None"),16 (property) onSome: (a: number) => void
onSome: ((parameter) value: number
value) => 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("Computed value:", (parameter) value: number
value) // At least one computation succeeded17})
Additionally, the Option.firstSomeOf
function can be used to retrieve the first value that is Some
within an iterable of Option
values:
1import { import Option
Option } from "effect"2
3const const first: Option.Option<number>
first = import Option
Option.const firstSomeOf: <unknown, (Option.None<number> | Option.Some<number>)[]>(collection: (Option.None<number> | Option.Some<number>)[]) => Option.Option<number>
Given an `Iterable` collection of `Option`s, returns the first `Some` found in the collection.
firstSomeOf([4 import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none(),5 import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(2),6 import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none(),7 import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(3)8]) // some(2)
When working with the Option
data type, you may come across code that uses undefined
or null
to represent optional values. The Option
data type provides several APIs to facilitate the interaction between Option
and nullable types.
You can create an Option
from a nullable value using the fromNullable
API.
1import { import Option
Option } from "effect"2
3import Option
Option.const fromNullable: <null>(nullableValue: null) => Option.Option<never>
Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise
returns the value wrapped in a `Some`.
fromNullable(null) // none()4import Option
Option.const fromNullable: <undefined>(nullableValue: undefined) => Option.Option<never>
Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise
returns the value wrapped in a `Some`.
fromNullable(var undefined
undefined) // none()5import Option
Option.const fromNullable: <number>(nullableValue: number) => Option.Option<number>
Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise
returns the value wrapped in a `Some`.
fromNullable(1) // some(1)
Conversely, if you have a value of type Option
and want to convert it to a nullable value, you have two options:
- Convert
None
tonull
using thegetOrNull
API. - Convert
None
toundefined
using thegetOrUndefined
API.
1import { import Option
Option } from "effect"2
3import Option
Option.const getOrNull: <number>(self: Option.Option<number>) => number | null
Returns the value of the `Option` if it is a `Some`, otherwise returns `null`.
getOrNull(import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(5)) // 54import Option
Option.const getOrNull: <never>(self: Option.Option<never>) => null
Returns the value of the `Option` if it is a `Some`, otherwise returns `null`.
getOrNull(import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none()) // null5
6import Option
Option.const getOrUndefined: <number>(self: Option.Option<number>) => number | undefined
Returns the value of the `Option` if it is a `Some`, otherwise returns `undefined`.
getOrUndefined(import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(5)) // 57import Option
Option.const getOrUndefined: <never>(self: Option.Option<never>) => undefined
Returns the value of the `Option` if it is a `Some`, otherwise returns `undefined`.
getOrUndefined(import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none()) // undefined
The Option
type is a subtype of the Effect
type, which means that it can be seamlessly used with functions from the Effect
module. These functions are primarily designed to work with Effect
values, but they can also handle Option
values and process them correctly.
In the context of Effect
, the two members of the Option
type are treated as follows:
None
is equivalent toEffect<never, NoSuchElementException>
Some<A>
is equivalent toEffect<A>
To illustrate this interoperability, let’s consider the following example:
1import { import Effect
Effect, import Option
Option } from "effect"2
3const const head: <A>(as: ReadonlyArray<A>) => Option.Option<A>
head = <(type parameter) A in <A>(as: ReadonlyArray<A>): Option.Option<A>
A>((parameter) as: readonly A[]
as: interface ReadonlyArray<T>
ReadonlyArray<(type parameter) A in <A>(as: ReadonlyArray<A>): Option.Option<A>
A>): import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<(type parameter) A in <A>(as: ReadonlyArray<A>): Option.Option<A>
A> =>4 (parameter) as: readonly A[]
as.(property) ReadonlyArray<A>.length: number
Gets the length of the array. This is a number one higher than the highest element defined in an array.
length > 0 ? import Option
Option.const some: <A>(value: A) => Option.Option<A>
Creates a new `Option` that wraps the given value.
some((parameter) as: readonly A[]
as[0]) : import Option
Option.const none: <A>() => Option.Option<A>
Creates a new `Option` that represents the absence of a value.
none()5
6namespace 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(7 import Effect
Effect.const runSync: <number, NoSuchElementException>(effect: Effect.Effect<number, NoSuchElementException, 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(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, 2, 3]).(method) Pipeable.pipe<Effect.Effect<number[], never, never>, Effect.Effect<number, NoSuchElementException, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number[], never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const andThen: <number[], Option.Option<number>>(f: (a: number[]) => Option.Option<number>) => <E, R>(self: Effect.Effect<number[], E, R>) => Effect.Effect<number, NoSuchElementException | E, R> (+3 overloads)
Executes a sequence of two actions, typically two `Effect`s, where the second action can depend on the result of the first action.
The `that` action can take various forms:
- a value
- a function returning a value
- a promise
- a function returning a promise
- an effect
- a function returning an effect
andThen(const head: <A>(as: ReadonlyArray<A>) => Option.Option<A>
head)))8) // Output: 19
10import Effect
Effect.const runSync: <never, NoSuchElementException>(effect: Effect.Effect<never, NoSuchElementException, never>) => never
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(import Effect
Effect.const succeed: <never[]>(value: never[]) => Effect.Effect<never[], 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([]).(method) Pipeable.pipe<Effect.Effect<never[], never, never>, Effect.Effect<never, NoSuchElementException, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<never[], never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const andThen: <never[], Option.Option<never>>(f: (a: never[]) => Option.Option<never>) => <E, R>(self: Effect.Effect<never[], E, R>) => Effect.Effect<never, NoSuchElementException | E, R> (+3 overloads)
Executes a sequence of two actions, typically two `Effect`s, where the second action can depend on the result of the first action.
The `that` action can take various forms:
- a value
- a function returning a value
- a promise
- a function returning a promise
- an effect
- a function returning an effect
andThen(const head: <A>(as: ReadonlyArray<A>) => Option.Option<A>
head))) // throws NoSuchElementException: undefined
The Option.zipWith
function allows you to combine two Option
values using a provided function. It creates a new Option
that holds the combined value of both original Option
values.
1import { import Option
Option } from "effect"2
3const const maybeName: Option.Option<string>
maybeName: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string> = import Option
Option.const some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
some("John")4const const maybeAge: Option.Option<number>
maybeAge: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number> = import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(25)5
6const const person: Option.Option<{
name: string;
age: number;
}>
person = import Option
Option.const zipWith: <string, number, {
name: string;
age: number;
}>(self: Option.Option<string>, that: Option.Option<number>, f: (a: string, b: number) => {
name: string;
age: number;
}) => Option.Option<{
name: string;
age: number;
}> (+1 overload)
Zips two `Option` values together using a provided function, returning a new `Option` of the result.
zipWith(const maybeName: Option.Option<string>
maybeName, const maybeAge: Option.Option<number>
maybeAge, ((parameter) name: string
name, (parameter) age: number
age) => ({7 (property) name: string
name: (parameter) name: string
name.(method) String.toUpperCase(): string
Converts all the alphabetic characters in a string to uppercase.
toUpperCase(),8 (property) age: number
age9}))10
11namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(const person: Option.Option<{
name: string;
age: number;
}>
person)12/*13Output:14{ _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }15*/
The Option.zipWith
function takes three arguments:
- The first
Option
you want to combine - The second
Option
you want to combine - A function that takes two arguments, which are the values held by the two
Options
, and returns the combined value
It’s important to note that if either of the two Option
values is None
, the resulting Option
will also be None
:
1import { import Option
Option } from "effect"2
3const const maybeName: Option.Option<string>
maybeName: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string> = import Option
Option.const some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
some("John")4const const maybeAge: Option.Option<number>
maybeAge: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number> = import Option
Option.const none: <number>() => Option.Option<number>
Creates a new `Option` that represents the absence of a value.
none()5
6const const person: Option.Option<{
name: string;
age: number;
}>
person = import Option
Option.const zipWith: <string, number, {
name: string;
age: number;
}>(self: Option.Option<string>, that: Option.Option<number>, f: (a: string, b: number) => {
name: string;
age: number;
}) => Option.Option<{
name: string;
age: number;
}> (+1 overload)
Zips two `Option` values together using a provided function, returning a new `Option` of the result.
zipWith(const maybeName: Option.Option<string>
maybeName, const maybeAge: Option.Option<number>
maybeAge, ((parameter) name: string
name, (parameter) age: number
age) => ({7 (property) name: string
name: (parameter) name: string
name.(method) String.toUpperCase(): string
Converts all the alphabetic characters in a string to uppercase.
toUpperCase(),8 (property) age: number
age9}))10
11namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(const person: Option.Option<{
name: string;
age: number;
}>
person)12/*13Output:14{ _id: 'Option', _tag: 'None' }15*/
If you need to combine two or more Option
s without transforming the values they hold, you can use Option.all
, which takes a collection of Option
s and returns an Option
with the same structure.
- If a tuple is provided, the returned
Option
will contain a tuple with the same length. - If a struct is provided, the returned
Option
will contain a struct with the same keys. - If an iterable is provided, the returned
Option
will contain an array.
1import { import Option
Option } from "effect"2
3const const maybeName: Option.Option<string>
maybeName: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string> = import Option
Option.const some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
some("John")4const const maybeAge: Option.Option<number>
maybeAge: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number> = import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(25)5
6const const tuple: Option.Option<[string, number]>
tuple = import Option
Option.const all: <readonly [Option.Option<string>, Option.Option<number>]>(input: readonly [Option.Option<string>, Option.Option<number>]) => Option.Option<[string, number]>
Takes a structure of `Option`s and returns an `Option` of values with the same structure.
- If a tuple is supplied, then the returned `Option` will contain a tuple with the same length.
- If a struct is supplied, then the returned `Option` will contain a struct with the same keys.
- If an iterable is supplied, then the returned `Option` will contain an array.
all([const maybeName: Option.Option<string>
maybeName, const maybeAge: Option.Option<number>
maybeAge])7
8const const struct: Option.Option<{
name: string;
age: number;
}>
struct = import Option
Option.const all: <{
readonly name: Option.Option<string>;
readonly age: Option.Option<number>;
}>(input: {
readonly name: Option.Option<string>;
readonly age: Option.Option<number>;
}) => Option.Option<...>
Takes a structure of `Option`s and returns an `Option` of values with the same structure.
- If a tuple is supplied, then the returned `Option` will contain a tuple with the same length.
- If a struct is supplied, then the returned `Option` will contain a struct with the same keys.
- If an iterable is supplied, then the returned `Option` will contain an array.
all({ (property) name: Option.Option<string>
name: const maybeName: Option.Option<string>
maybeName, (property) age: Option.Option<number>
age: const maybeAge: Option.Option<number>
maybeAge })
Similar to Effect.gen, there’s also Option.gen
, which provides a convenient syntax, akin to async/await, for writing code involving Option
and using generators.
Let’s revisit the previous example, this time using Option.gen
instead of Option.zipWith
:
1import { import Option
Option } from "effect"2
3const const maybeName: Option.Option<string>
maybeName: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string> = import Option
Option.const some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
some("John")4const const maybeAge: Option.Option<number>
maybeAge: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number> = import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(25)5
6const const person: Option.Option<{
name: string;
age: number;
}>
person = import Option
Option.const gen: Gen
<unknown, YieldWrap<Option.None<string>> | YieldWrap<Option.Some<string>> | YieldWrap<Option.None<number>> | YieldWrap<Option.Some<number>>, {
...;
}>(...args: [self: ...] | [body: ...]) => Option.Option<...>
gen(function* () {7 const const name: string
name = (yield* const maybeName: Option.Option<string>
maybeName).(method) String.toUpperCase(): string
Converts all the alphabetic characters in a string to uppercase.
toUpperCase()8 const const age: number
age = yield* const maybeAge: Option.Option<number>
maybeAge9 return { (property) name: string
name, (property) age: number
age }10})11
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(const person: Option.Option<{
name: string;
age: number;
}>
person)13/*14Output:15{ _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }16*/
Once again, if either of the two Option
values is None
, the resulting Option
will also be None
:
1import { import Option
Option } from "effect"2
3const const maybeName: Option.Option<string>
maybeName: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<string> = import Option
Option.const some: <string>(value: string) => Option.Option<string>
Creates a new `Option` that wraps the given value.
some("John")4const const maybeAge: Option.Option<number>
maybeAge: import Option
Option.type Option<A> = Option.None<A> | Option.Some<A>
namespace Option
Option<number> = import Option
Option.const none: <number>() => Option.Option<number>
Creates a new `Option` that represents the absence of a value.
none()5
6const const person: Option.Option<{
name: string;
age: number;
}>
person = import Option
Option.const gen: Gen
<unknown, YieldWrap<Option.None<string>> | YieldWrap<Option.Some<string>> | YieldWrap<Option.None<number>> | YieldWrap<Option.Some<number>>, {
...;
}>(...args: [self: ...] | [body: ...]) => Option.Option<...>
gen(function* () {7 const const name: string
name = (yield* const maybeName: Option.Option<string>
maybeName).(method) String.toUpperCase(): string
Converts all the alphabetic characters in a string to uppercase.
toUpperCase()8 const const age: number
age = yield* const maybeAge: Option.Option<number>
maybeAge9 return { (property) name: string
name, (property) age: number
age }10})11
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(const person: Option.Option<{
name: string;
age: number;
}>
person)13/*14Output:15{ _id: 'Option', _tag: 'None' }16*/
You can compare Option
values using the Option.getEquivalence
function.
This function lets you define rules for comparing the contents of Option
types by providing an Equivalence
for the type of value they might contain.
Example (Checking Equivalence of Optional Numbers)
Imagine you have optional numbers and you want to check if they are equivalent. Here’s how you can do it:
1import { import Option
Option, import Equivalence
Equivalence } from "effect"2
3const const myEquivalence: Equivalence.Equivalence<Option.Option<number>>
myEquivalence = import Option
Option.const getEquivalence: <number>(isEquivalent: Equivalence.Equivalence<number>) => Equivalence.Equivalence<Option.Option<number>>
getEquivalence(import Equivalence
Equivalence.const number: Equivalence.Equivalence<number>
number)4
5namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(const myEquivalence: Equivalence.Equivalence
(self: Option.Option<number>, that: Option.Option<number>) => boolean
myEquivalence(import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(1), import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(1))) // Output: true, because both options contain the number 16namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(const myEquivalence: Equivalence.Equivalence
(self: Option.Option<number>, that: Option.Option<number>) => boolean
myEquivalence(import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(1), import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(2))) // Output: false, because the numbers are different7namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(const myEquivalence: Equivalence.Equivalence
(self: Option.Option<number>, that: Option.Option<number>) => boolean
myEquivalence(import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(1), import Option
Option.const none: <number>() => Option.Option<number>
Creates a new `Option` that represents the absence of a value.
none())) // Output: false, because one is a number and the other is empty
Sorting a collection of Option
values can be done using the Option.getOrder
function.
This function helps you sort Option
values by providing a custom sorting rule for the type of value they might contain.
Example (Sorting Optional Numbers)
Suppose you have a list of optional numbers and you want to sort them in ascending order, considering empty values as the lowest:
1import { import Option
Option, import Array
Array, import Order
Order } from "effect"2
3const const items: (Option.None<number> | Option.Some<number>)[]
items = [import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(1), import Option
Option.const none: <never>() => Option.Option<never>
Creates a new `Option` that represents the absence of a value.
none(), import Option
Option.const some: <number>(value: number) => Option.Option<number>
Creates a new `Option` that wraps the given value.
some(2)]4
5const const myOrder: Order.Order<Option.Option<number>>
myOrder = import Option
Option.const getOrder: <number>(O: Order.Order<number>) => Order.Order<Option.Option<number>>
The `Order` instance allows `Option` values to be compared with
`compare`, whenever there is an `Order` instance for
the type the `Option` contains.
`None` is considered to be less than any `Some` value.
getOrder(import Order
Order.const number: Order.Order<number>
number)6
7namespace 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 Array
Array.const sort: <Option.Option<number>>(O: Order.Order<Option.Option<number>>) => <A, S>(self: S) => Array.ReadonlyArray.With<S, Array.ReadonlyArray.Infer<S>> (+2 overloads)
Create a new array with elements sorted in increasing order based on the specified comparator.
If the input is a `NonEmptyReadonlyArray`, the output will also be a `NonEmptyReadonlyArray`.
sort(const myOrder: Order.Order<Option.Option<number>>
myOrder)(const items: (Option.None<number> | Option.Some<number>)[]
items))8/*9Output:10[11 { _id: 'Option', _tag: 'None' }, // None appears first because it's considered the lowest12 { _id: 'Option', _tag: 'Some', value: 1 }, // Sorted in ascending order13 { _id: 'Option', _tag: 'Some', value: 2 }14]15*/
In this example, Option.none()
is treated as the lowest value, allowing Option.some(1)
and Option.some(2)
to be sorted in ascending order based on their numerical value. This method ensures that all Option
values are sorted logically according to their content, with empty values (Option.none()
) being placed before non-empty values (Option.some()
).
Advanced Example: Sorting Optional Dates in Reverse Order
Now, let’s consider a more complex scenario where you have a list of objects containing optional dates, and you want to sort them in descending order, with any empty optional values placed at the end:
1import { Option, Array, Order } from "effect"2
3const items = [4 { data: Option.some(new Date(10)) },5 { data: Option.some(new Date(20)) },6 { data: Option.none() }7]8
9// Define the order to sort dates within Option values in reverse10const sorted = Array.sortWith(11 items,12 (item) => item.data,13 Order.reverse(Option.getOrder(Order.Date))14)15
16console.log(sorted)17/*18Output:19[20 { data: { _id: 'Option', _tag: 'Some', value: '1970-01-01T00:00:00.020Z' } },21 { data: { _id: 'Option', _tag: 'Some', value: '1970-01-01T00:00:00.010Z' } },22 { data: { _id: 'Option', _tag: 'None' } } // None placed last23]24*/