Skip to content

Option

Option 数据类型表示可选值。Option<A> 可以是 Some<A>(包含类型为 A 的值)或 None(表示值的缺失)。

您可以在以下场景中使用 Option

  • 用于初始值
  • 从并非对所有可能输入都有定义的函数中返回值(称为”偏函数”)
  • 管理数据结构中的可选字段
  • 处理可选的函数参数

使用 Option.some 构造函数创建一个保存类型为 A 的值的 Option

示例(创建带有值的 Option)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
// 一个保存数字 1 的 Option
const
const value: Option.Option<number>
value
=
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(1)
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const value: Option.Option<number>
value
)
// 输出: { _id: 'Option', _tag: 'Some', value: 1 }

使用 Option.none 构造函数创建一个表示值缺失的 Option

示例(创建没有值的 Option)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
// 一个不保存任何值的 Option
const
const noValue: Option.Option<never>
noValue
=
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const noValue: Option.Option<never>
noValue
)
// 输出: { _id: 'Option', _tag: 'None' }

您可以基于谓词创建 Option,例如,检查值是否为正数。

示例(使用显式 Option 创建)

以下是使用 Option.noneOption.some 实现此功能的方法:

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const isPositive: (n: number) => boolean
isPositive
= (
n: number
n
: number) =>
n: number
n
> 0
const
const parsePositive: (n: number) => Option.Option<number>
parsePositive
= (
n: number
n
: number):
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<number> =>
const isPositive: (n: number) => boolean
isPositive
(
n: number
n
) ?
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(
n: number
n
) :
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <number>() => Option.Option<number>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()

示例(使用 Option.liftPredicate 简化)

或者,您可以使用 Option.liftPredicate 简化上述逻辑:

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const isPositive: (n: number) => boolean
isPositive
= (
n: number
n
: number) =>
n: number
n
> 0
// ┌─── (b: number) => Option<number>
// ▼
const
const parsePositive: (b: number) => Option.Option<number>
parsePositive
=
import Option

@since2.0.0

@since2.0.0

Option
.
const liftPredicate: <number, number>(predicate: Predicate<number>) => (b: number) => Option.Option<number> (+3 overloads)

Lifts a Predicate or Refinement into the Option context, returning a Some of the input value if the predicate is satisfied, or None otherwise.

Details

This function transforms a Predicate (or a more specific Refinement) into a function that produces an Option. If the predicate evaluates to true, the input value is wrapped in a Some. If the predicate evaluates to false, the result is None.

@example

import { Option } from "effect"
// Check if a number is positive
const isPositive = (n: number) => n > 0
// ┌─── (b: number) => Option<number>
// ▼
const parsePositive = Option.liftPredicate(isPositive)
console.log(parsePositive(1))
// Output: { _id: 'Option', _tag: 'Some', value: 1 }
console.log(parsePositive(-1))
// OUtput: { _id: 'Option', _tag: 'None' }

@since2.0.0

liftPredicate
(
const isPositive: (n: number) => boolean
isPositive
)

考虑一个 User 模型,其中 "email" 属性是可选的,可以保存 string 值。我们使用 Option<string> 类型来表示这个可选属性:

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
interface
interface User
User
{
readonly
User.id: number
id
: number
readonly
User.username: string
username
: string
readonly
User.email: Option.Option<string>
email
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string>
}

以下是如何创建有和没有电子邮件的 User 实例的示例:

示例(创建有和没有电子邮件的用户)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
interface
interface User
User
{
readonly
User.id: number
id
: number
readonly
User.username: string
username
: string
readonly
User.email: Option.Option<string>
email
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string>
}
const
const withEmail: User
withEmail
:
interface User
User
= {
User.id: number
id
: 1,
User.username: string
username
: "john_doe",
User.email: Option.Option<string>
email
:
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("john.doe@example.com")
}
const
const withoutEmail: User
withoutEmail
:
interface User
User
= {
User.id: number
id
: 2,
User.username: string
username
: "jane_doe",
User.email: Option.Option<string>
email
:
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <string>() => Option.Option<string>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
}

您可以使用 Option.isSomeOption.isNone 守卫检查 OptionSome 还是 None

示例(使用守卫检查 Option 值)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const foo: Option.Option<number>
foo
=
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(1)
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const isSome: <number>(self: Option.Option<number>) => self is Option.Some<number>

Checks whether an Option contains a value (Some).

@example

import { Option } from "effect"
console.log(Option.isSome(Option.some(1)))
// Output: true
console.log(Option.isSome(Option.none()))
// Output: false

@seeisNone for the opposite check.

@since2.0.0

isSome
(
const foo: Option.Option<number>
foo
))
// 输出: true
if (
import Option

@since2.0.0

@since2.0.0

Option
.
const isNone: <number>(self: Option.Option<number>) => self is Option.None<number>

Checks whether an Option represents the absence of a value (None).

@example

import { Option } from "effect"
console.log(Option.isNone(Option.some(1)))
// Output: false
console.log(Option.isNone(Option.none()))
// Output: true

@seeisSome for the opposite check.

@since2.0.0

isNone
(
const foo: Option.Option<number>
foo
)) {
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
("Option 为空")
} else {
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(`Option 有一个值: ${
const foo: Option.Some<number>
foo
.
Some<number>.value: number
value
}`)
}
// 输出: "Option 有一个值: 1"

使用 Option.match 通过为 NoneSome 指定单独的回调来处理 Option 的两种情况。

示例(使用 Option 进行模式匹配)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const foo: Option.Option<number>
foo
=
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(1)
const
const message: string
message
=
import Option

@since2.0.0

@since2.0.0

Option
.
const match: <number, string, string>(self: Option.Option<number>, options: {
readonly onNone: LazyArg<string>;
readonly onSome: (a: number) => string;
}) => string (+1 overload)

Performs pattern matching on an Option to handle both Some and None cases.

Details

This function allows you to match against an Option and handle both scenarios: when the Option is None (i.e., contains no value), and when the Option is Some (i.e., contains a value). It executes one of the provided functions based on the case:

  • If the Option is None, the onNone function is executed and its result is returned.
  • If the Option is Some, the onSome function is executed with the contained value, and its result is returned.

This function provides a concise and functional way to handle optional values without resorting to if or manual checks, making your code more declarative and readable.

Example (Pattern Matching with Option)

import { Option } from "effect"
const foo = Option.some(1)
const message = Option.match(foo, {
onNone: () => "Option is empty",
onSome: (value) => `Option has a value: ${value}`
})
console.log(message)
// Output: "Option has a value: 1"

@since2.0.0

match
(
const foo: Option.Option<number>
foo
, {
onNone: LazyArg<string>
onNone
: () => "Option 为空",
onSome: (a: number) => string
onSome
: (
value: number
value
) => `Option 有一个值: ${
value: number
value
}`
})
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const message: string
message
)
// 输出: "Option 有一个值: 1"

Option.map 函数允许您转换 Option 内部的值,而无需手动解包和重新包装。如果 Option 保存一个值(Some),则应用转换函数。如果 OptionNone,则忽略该函数,Option 保持不变。

示例(映射 Some 中的值)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
// 转换 Some 内部的值
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const map: <number, number>(self: Option.Option<number>, f: (a: number) => number) => Option.Option<number> (+1 overload)

Transforms the value inside a Some to a new value using the provided function, while leaving None unchanged.

Details

This function applies a mapping function f to the value inside an Option if it is a Some. If the Option is None, it remains unchanged. The result is a new Option with the transformed value (if it was a Some) or still None.

This utility is particularly useful for chaining transformations in a functional way without needing to manually handle None cases.

@example

import { Option } from "effect"
// Mapping over a `Some`
const someValue = Option.some(2)
console.log(Option.map(someValue, (n) => n * 2))
// Output: { _id: 'Option', _tag: 'Some', value: 4 }
// Mapping over a `None`
const noneValue = Option.none<number>()
console.log(Option.map(noneValue, (n) => n * 2))
// Output: { _id: 'Option', _tag: 'None' }

@since2.0.0

map
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(1), (
n: number
n
) =>
n: number
n
+ 1))
// 输出: { _id: 'Option', _tag: 'Some', value: 2 }

当处理 None 时,映射函数不会执行,Option 保持为 None

示例(映射 None)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
// 映射 None 结果仍为 None
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const map: <never, number>(self: Option.Option<never>, f: (a: never) => number) => Option.Option<number> (+1 overload)

Transforms the value inside a Some to a new value using the provided function, while leaving None unchanged.

Details

This function applies a mapping function f to the value inside an Option if it is a Some. If the Option is None, it remains unchanged. The result is a new Option with the transformed value (if it was a Some) or still None.

This utility is particularly useful for chaining transformations in a functional way without needing to manually handle None cases.

@example

import { Option } from "effect"
// Mapping over a `Some`
const someValue = Option.some(2)
console.log(Option.map(someValue, (n) => n * 2))
// Output: { _id: 'Option', _tag: 'Some', value: 4 }
// Mapping over a `None`
const noneValue = Option.none<number>()
console.log(Option.map(noneValue, (n) => n * 2))
// Output: { _id: 'Option', _tag: 'None' }

@since2.0.0

map
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
(), (
n: never
n
) =>
n: never
n
+ 1))
// 输出: { _id: 'Option', _tag: 'None' }

Option.flatMap 函数类似于 Option.map,但它专为处理转换可能返回另一个 Option 的情况而设计。这允许我们链接依赖于 Option 中是否存在值的计算。

考虑一个包含嵌套可选 AddressUser 模型,该 Address 本身包含一个可选的 street 属性:

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
interface
interface User
User
{
readonly
User.id: number
id
: number
readonly
User.username: string
username
: string
readonly
User.email: Option.Option<string>
email
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string>
readonly
User.address: Option.Option<Address>
address
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<
interface Address
Address
>
}
interface
interface Address
Address
{
readonly
Address.city: string
city
: string
readonly
Address.street: Option.Option<string>
street
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string>
}

在此模型中,address 字段是 Option<Address>Address 内的 street 字段是 Option<string>

我们可以使用 Option.flatMapaddress 中提取 street 属性:

示例(提取嵌套的可选属性)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
interface
interface Address
Address
{
readonly
Address.city: string
city
: string
readonly
Address.street: Option.Option<string>
street
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string>
}
interface
interface User
User
{
readonly
User.id: number
id
: number
readonly
User.username: string
username
: string
readonly
User.email: Option.Option<string>
email
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string>
readonly
User.address: Option.Option<Address>
address
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<
interface Address
Address
>
}
const
const user: User
user
:
interface User
User
= {
User.id: number
id
: 1,
User.username: string
username
: "john_doe",
User.email: Option.Option<string>
email
:
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("john.doe@example.com"),
User.address: Option.Option<Address>
address
:
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <{
city: string;
street: Option.Option<string>;
}>(value: {
city: string;
street: Option.Option<string>;
}) => Option.Option<{
city: string;
street: Option.Option<string>;
}>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
({
city: string
city
: "New York",
street: Option.Option<string>
street
:
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("123 Main St")
})
}
// 使用 flatMap 提取街道值
const
const street: Option.Option<string>
street
=
const user: User
user
.
User.address: Option.Option<Address>
address
.
Pipeable.pipe<Option.Option<Address>, Option.Option<string>>(this: Option.Option<Address>, ab: (_: Option.Option<Address>) => Option.Option<string>): Option.Option<string> (+21 overloads)
pipe
(
import Option

@since2.0.0

@since2.0.0

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 a Some and flattens the resulting Option. If the input is None, it remains None.

Details

This function allows you to chain computations that return Option values. If the input Option is Some, the provided function f is applied to the contained value, and the resulting Option is returned. If the input is None, the function is not applied, and the result remains None.

This utility is particularly useful for sequencing operations that may fail or produce optional results, enabling clean and concise workflows for handling such cases.

@example

import { Option } from "effect"
interface Address {
readonly city: string
readonly street: Option.Option<string>
}
interface User {
readonly id: number
readonly username: string
readonly email: Option.Option<string>
readonly address: Option.Option<Address>
}
const user: User = {
id: 1,
username: "john_doe",
email: Option.some("john.doe@example.com"),
address: Option.some({
city: "New York",
street: Option.some("123 Main St")
})
}
// Use flatMap to extract the street value
const street = user.address.pipe(
Option.flatMap((address) => address.street)
)
console.log(street)
// Output: { _id: 'Option', _tag: 'Some', value: '123 Main St' }

@since2.0.0

flatMap
((
address: Address
address
) =>
address: Address
address
.
Address.street: Option.Option<string>
street
)
)
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const street: Option.Option<string>
street
)
// 输出: { _id: 'Option', _tag: 'Some', value: '123 Main St' }

如果 user.addressSomeOption.flatMap 应用函数 (address) => address.street 来检索 street 值。

如果 user.addressNone,则不执行该函数,street 保持为 None

这种方法让我们能够简洁地处理嵌套的可选值,避免手动检查,使代码更清洁、更易读。

Option.filter 函数允许您基于给定的谓词过滤 Option。如果不满足谓词或 OptionNone,结果将是 None

示例(过滤 Option 值)

以下是如何使用 Option.filter 简化一些代码以获得更惯用的方法:

原始代码

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
// 从 Option 中删除空字符串的函数
const
const removeEmptyString: (input: Option.Option<string>) => Option.None<string> | Option.Some<string>
removeEmptyString
= (
input: Option.Option<string>
input
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string>) => {
if (
import Option

@since2.0.0

@since2.0.0

Option
.
const isSome: <string>(self: Option.Option<string>) => self is Option.Some<string>

Checks whether an Option contains a value (Some).

@example

import { Option } from "effect"
console.log(Option.isSome(Option.some(1)))
// Output: true
console.log(Option.isSome(Option.none()))
// Output: false

@seeisNone for the opposite check.

@since2.0.0

isSome
(
input: Option.Option<string>
input
) &&
input: Option.Some<string>
input
.
Some<string>.value: string
value
=== "") {
return
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
() // 如果值是空字符串则返回 None
}
return
input: Option.Option<string>
input
// 否则,返回原始 Option
}
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const removeEmptyString: (input: Option.Option<string>) => Option.None<string> | Option.Some<string>
removeEmptyString
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <string>() => Option.Option<string>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()))
// 输出: { _id: 'Option', _tag: 'None' }
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const removeEmptyString: (input: Option.Option<string>) => Option.None<string> | Option.Some<string>
removeEmptyString
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("")))
// 输出: { _id: 'Option', _tag: 'None' }
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const removeEmptyString: (input: Option.Option<string>) => Option.None<string> | Option.Some<string>
removeEmptyString
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("a")))
// 输出: { _id: 'Option', _tag: 'Some', value: 'a' }

重构的惯用代码

使用 Option.filter,我们可以更简洁地编写相同的逻辑:

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const removeEmptyString: (input: Option.Option<string>) => Option.Option<string>
removeEmptyString
= (
input: Option.Option<string>
input
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string>) =>
import Option

@since2.0.0

@since2.0.0

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.

@example

import { Option } from "effect"
const removeEmptyString = (input: Option.Option<string>) =>
Option.filter(input, (value) => value !== "")
console.log(removeEmptyString(Option.none()))
// Output: { _id: 'Option', _tag: 'None' }
console.log(removeEmptyString(Option.some("")))
// Output: { _id: 'Option', _tag: 'None' }
console.log(removeEmptyString(Option.some("a")))
// Output: { _id: 'Option', _tag: 'Some', value: 'a' }

@since2.0.0

filter
(
input: Option.Option<string>
input
, (
value: string
value
) =>
value: string
value
!== "")
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const removeEmptyString: (input: Option.Option<string>) => Option.Option<string>
removeEmptyString
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <string>() => Option.Option<string>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()))
// 输出: { _id: 'Option', _tag: 'None' }
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const removeEmptyString: (input: Option.Option<string>) => Option.Option<string>
removeEmptyString
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("")))
// 输出: { _id: 'Option', _tag: 'None' }
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const removeEmptyString: (input: Option.Option<string>) => Option.Option<string>
removeEmptyString
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("a")))
// 输出: { _id: 'Option', _tag: 'Some', value: 'a' }

要检索存储在 Option 内部的值,您可以使用 Option 模块提供的几个辅助函数。以下是可用方法的概述:

此函数从 Some 中提取值。如果 OptionNone,它会抛出错误。

示例(检索值或抛出错误)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrThrow: <number>(self: Option.Option<number>) => number

Extracts the value of an Option or throws a default error if the Option is None.

Details

This function extracts the value from an Option if it is Some. If the Option is None, it throws a default error. It is useful for fail-fast scenarios where the absence of a value is treated as an exceptional case and a default error is sufficient.

@example

import * as assert from "node:assert"
import { Option } from "effect"
assert.deepStrictEqual(Option.getOrThrow(Option.some(1)), 1)
assert.throws(() => Option.getOrThrow(Option.none()))

@seegetOrThrowWith for a version that allows you to provide a custom error.

@since2.0.0

getOrThrow
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(10)))
// 输出: 10
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrThrow: <any>(self: Option.Option<any>) => any

Extracts the value of an Option or throws a default error if the Option is None.

Details

This function extracts the value from an Option if it is Some. If the Option is None, it throws a default error. It is useful for fail-fast scenarios where the absence of a value is treated as an exceptional case and a default error is sufficient.

@example

import * as assert from "node:assert"
import { Option } from "effect"
assert.deepStrictEqual(Option.getOrThrow(Option.some(1)), 1)
assert.throws(() => Option.getOrThrow(Option.none()))

@seegetOrThrowWith for a version that allows you to provide a custom error.

@since2.0.0

getOrThrow
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <any>() => Option.Option<any>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()))
// 抛出: Error: getOrThrow called on a None

这些函数将 None 转换为 nullundefined,这在使用非基于 Option 的代码时很有用。

示例(将 None 转换为 nullundefined

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrNull: <number>(self: Option.Option<number>) => number | null

Returns the value contained in the Option if it is Some; otherwise, returns null.

Details

This function provides a way to extract the value of an Option while falling back to null if the Option is None.

It is particularly useful in scenarios where null is an acceptable placeholder for the absence of a value, such as when interacting with APIs or systems that use null as a default for missing values.

@example

import { Option } from "effect"
console.log(Option.getOrNull(Option.some(1)))
// Output: 1
console.log(Option.getOrNull(Option.none()))
// Output: null

@since2.0.0

getOrNull
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(5)))
// 输出: 5
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrNull: <any>(self: Option.Option<any>) => any

Returns the value contained in the Option if it is Some; otherwise, returns null.

Details

This function provides a way to extract the value of an Option while falling back to null if the Option is None.

It is particularly useful in scenarios where null is an acceptable placeholder for the absence of a value, such as when interacting with APIs or systems that use null as a default for missing values.

@example

import { Option } from "effect"
console.log(Option.getOrNull(Option.some(1)))
// Output: 1
console.log(Option.getOrNull(Option.none()))
// Output: null

@since2.0.0

getOrNull
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <any>() => Option.Option<any>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()))
// 输出: null
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrUndefined: <number>(self: Option.Option<number>) => number | undefined

Returns the value contained in the Option if it is Some; otherwise, returns undefined.

Details

This function provides a way to extract the value of an Option while falling back to undefined if the Option is None.

It is particularly useful in scenarios where undefined is an acceptable placeholder for the absence of a value, such as when interacting with APIs or systems that use undefined as a default for missing values.

@example

import { Option } from "effect"
console.log(Option.getOrUndefined(Option.some(1)))
// Output: 1
console.log(Option.getOrUndefined(Option.none()))
// Output: undefined

@since2.0.0

getOrUndefined
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(5)))
// 输出: 5
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrUndefined: <any>(self: Option.Option<any>) => any

Returns the value contained in the Option if it is Some; otherwise, returns undefined.

Details

This function provides a way to extract the value of an Option while falling back to undefined if the Option is None.

It is particularly useful in scenarios where undefined is an acceptable placeholder for the absence of a value, such as when interacting with APIs or systems that use undefined as a default for missing values.

@example

import { Option } from "effect"
console.log(Option.getOrUndefined(Option.some(1)))
// Output: 1
console.log(Option.getOrUndefined(Option.none()))
// Output: undefined

@since2.0.0

getOrUndefined
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <any>() => Option.Option<any>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()))
// 输出: undefined

此函数允许您指定当 OptionNone 时要返回的默认值。

示例(当 None 时提供默认值)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrElse: <number, number>(self: Option.Option<number>, onNone: LazyArg<number>) => number (+1 overload)

Returns the value contained in the Option if it is Some, otherwise evaluates and returns the result of onNone.

Details

This function allows you to provide a fallback value or computation for when an Option is None. If the Option contains a value (Some), that value is returned. If it is empty (None), the onNone function is executed, and its result is returned instead.

This utility is helpful for safely handling Option values by ensuring you always receive a meaningful result, whether or not the Option contains a value. It is particularly useful for providing default values or alternative logic when working with optional values.

@example

import { Option } from "effect"
console.log(Option.some(1).pipe(Option.getOrElse(() => 0)))
// Output: 1
console.log(Option.none().pipe(Option.getOrElse(() => 0)))
// Output: 0

@seegetOrNull for a version that returns null instead of executing a function.

@seegetOrUndefined for a version that returns undefined instead of executing a function.

@since2.0.0

getOrElse
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(5), () => 0))
// 输出: 5
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrElse: <any, number>(self: Option.Option<any>, onNone: LazyArg<number>) => any (+1 overload)

Returns the value contained in the Option if it is Some, otherwise evaluates and returns the result of onNone.

Details

This function allows you to provide a fallback value or computation for when an Option is None. If the Option contains a value (Some), that value is returned. If it is empty (None), the onNone function is executed, and its result is returned instead.

This utility is helpful for safely handling Option values by ensuring you always receive a meaningful result, whether or not the Option contains a value. It is particularly useful for providing default values or alternative logic when working with optional values.

@example

import { Option } from "effect"
console.log(Option.some(1).pipe(Option.getOrElse(() => 0)))
// Output: 1
console.log(Option.none().pipe(Option.getOrElse(() => 0)))
// Output: 0

@seegetOrNull for a version that returns null instead of executing a function.

@seegetOrUndefined for a version that returns undefined instead of executing a function.

@since2.0.0

getOrElse
(
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <any>() => Option.Option<any>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
(), () => 0))
// 输出: 0

当计算返回 None 时,您可能想要尝试产生 Option 的替代计算。Option.orElse 函数在这种情况下很有用。它让您链接多个计算,如果当前计算结果为 None,则继续下一个。这种方法通常用于重试逻辑,尝试计算直到一个成功或所有可能性都用尽。

示例(尝试替代计算)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
// 模拟可能产生或不产生结果的计算
const
const computation: () => Option.Option<number>
computation
= ():
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<number> =>
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() < 0.5 ?
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(10) :
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <number>() => Option.Option<number>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
// 模拟替代计算
const
const alternativeComputation: () => Option.Option<number>
alternativeComputation
= ():
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<number> =>
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() < 0.5 ?
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(20) :
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <number>() => Option.Option<number>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
// 尝试第一个计算,如果需要则尝试替代方案
const
const program: Option.Option<number>
program
=
const computation: () => Option.Option<number>
computation
().
Pipeable.pipe<Option.Option<number>, Option.Option<number>>(this: Option.Option<number>, ab: (_: Option.Option<number>) => Option.Option<number>): Option.Option<number> (+21 overloads)
pipe
(
import Option

@since2.0.0

@since2.0.0

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 the current Option (self) is None; otherwise, it returns self.

Details

This function provides a fallback mechanism for Option values. If the current Option is None (i.e., it contains no value), the that function is evaluated, and its resulting Option is returned. If the current Option is Some (i.e., it contains a value), the original Option is returned unchanged.

This is particularly useful for chaining fallback values or computations, allowing you to provide alternative Option values when the first one is empty.

@example

import { Option } from "effect"
console.log(Option.none().pipe(Option.orElse(() => Option.none())))
// Output: { _id: 'Option', _tag: 'None' }
console.log(Option.some("a").pipe(Option.orElse(() => Option.none())))
// Output: { _id: 'Option', _tag: 'Some', value: 'a' }
console.log(Option.none().pipe(Option.orElse(() => Option.some("b"))))
// Output: { _id: 'Option', _tag: 'Some', value: 'b' }
console.log(Option.some("a").pipe(Option.orElse(() => Option.some("b"))))
// Output: { _id: 'Option', _tag: 'Some', value: 'a' }

@since2.0.0

orElse
(() =>
const alternativeComputation: () => Option.Option<number>
alternativeComputation
())
)
const
const result: string
result
=
import Option

@since2.0.0

@since2.0.0

Option
.
const match: <number, string, string>(self: Option.Option<number>, options: {
readonly onNone: LazyArg<string>;
readonly onSome: (a: number) => string;
}) => string (+1 overload)

Performs pattern matching on an Option to handle both Some and None cases.

Details

This function allows you to match against an Option and handle both scenarios: when the Option is None (i.e., contains no value), and when the Option is Some (i.e., contains a value). It executes one of the provided functions based on the case:

  • If the Option is None, the onNone function is executed and its result is returned.
  • If the Option is Some, the onSome function is executed with the contained value, and its result is returned.

This function provides a concise and functional way to handle optional values without resorting to if or manual checks, making your code more declarative and readable.

Example (Pattern Matching with Option)

import { Option } from "effect"
const foo = Option.some(1)
const message = Option.match(foo, {
onNone: () => "Option is empty",
onSome: (value) => `Option has a value: ${value}`
})
console.log(message)
// Output: "Option has a value: 1"

@since2.0.0

match
(
const program: Option.Option<number>
program
, {
onNone: LazyArg<string>
onNone
: () => "两个计算都导致 None",
// 至少有一个计算成功
onSome: (a: number) => string
onSome
: (
value: number
value
) => `计算值: ${
value: number
value
}`
})
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const result: string
result
)
// 输出: 计算值: 10

您还可以使用 Option.firstSomeOfOption 值的可迭代对象中获取第一个 Some 值:

示例(检索第一个 Some 值)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const first: Option.Option<number>
first
=
import Option

@since2.0.0

@since2.0.0

Option
.
const firstSomeOf: <unknown, (Option.None<number> | Option.Some<number>)[]>(collection: (Option.None<number> | Option.Some<number>)[]) => Option.Option<number>

Returns the first Some value found in an Iterable collection of Options, or None if no Some is found.

Details

This function iterates over a collection of Option values and returns the first Some it encounters. If the collection contains only None values, the result will also be None. This utility is useful for efficiently finding the first valid value in a sequence of potentially empty or invalid options.

The iteration stops as soon as a Some is found, making this function efficient for large collections.

@example

import { Option } from "effect"
console.log(Option.firstSomeOf([
Option.none(),
Option.some(1),
Option.some(2)
]))
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@since2.0.0

firstSomeOf
([
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
(),
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(2),
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
(),
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(3)
])
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const first: Option.Option<number>
first
)
// 输出: { _id: 'Option', _tag: 'Some', value: 2 }

在处理 Option 数据类型时,您可能会遇到使用 undefinednull 来表示可选值的代码。Option 模块提供了几个 API 来简化与这些可空类型的交互。

Option.fromNullable 将可空值(nullundefined)转换为 Option。如果值是 nullundefined,它返回 Option.none()。否则,它将值包装在 Option.some() 中。

示例(从可空值创建 Option)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const fromNullable: <null>(nullableValue: null) => Option.Option<never>

Converts a nullable value into an Option. Returns None if the value is null or undefined, otherwise wraps the value in a Some.

@example

import { Option } from "effect"
console.log(Option.fromNullable(undefined))
// Output: { _id: 'Option', _tag: 'None' }
console.log(Option.fromNullable(null))
// Output: { _id: 'Option', _tag: 'None' }
console.log(Option.fromNullable(1))
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@since2.0.0

fromNullable
(null))
// 输出: { _id: 'Option', _tag: 'None' }
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const fromNullable: <undefined>(nullableValue: undefined) => Option.Option<never>

Converts a nullable value into an Option. Returns None if the value is null or undefined, otherwise wraps the value in a Some.

@example

import { Option } from "effect"
console.log(Option.fromNullable(undefined))
// Output: { _id: 'Option', _tag: 'None' }
console.log(Option.fromNullable(null))
// Output: { _id: 'Option', _tag: 'None' }
console.log(Option.fromNullable(1))
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@since2.0.0

fromNullable
(
var undefined
undefined
))
// 输出: { _id: 'Option', _tag: 'None' }
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
import Option

@since2.0.0

@since2.0.0

Option
.
const fromNullable: <number>(nullableValue: number) => Option.Option<number>

Converts a nullable value into an Option. Returns None if the value is null or undefined, otherwise wraps the value in a Some.

@example

import { Option } from "effect"
console.log(Option.fromNullable(undefined))
// Output: { _id: 'Option', _tag: 'None' }
console.log(Option.fromNullable(null))
// Output: { _id: 'Option', _tag: 'None' }
console.log(Option.fromNullable(1))
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@since2.0.0

fromNullable
(1))
// 输出: { _id: 'Option', _tag: 'Some', value: 1 }

如果您需要将 Option 转换回可空值,有两个辅助方法:

  • Option.getOrNull:将 None 转换为 null
  • Option.getOrUndefined:将 None 转换为 undefined

Option 类型作为 Effect 类型的子类型工作,允许您将其与 Effect 模块中的函数一起使用。虽然这些函数是为处理 Effect 值而构建的,但它们也可以正确管理 Option 值。

Option 变体映射到 Effect描述
NoneEffect<never, NoSuchElementException>表示值的缺失
Some<A>Effect<A>表示值的存在

示例(将 OptionEffect 结合)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
// 获取数组头部的函数,返回 Option
const
const head: <A>(array: ReadonlyArray<A>) => Option.Option<A>
head
= <
function (type parameter) A in <A>(array: ReadonlyArray<A>): Option.Option<A>
A
>(
array: readonly A[]
array
:
interface ReadonlyArray<T>
ReadonlyArray
<
function (type parameter) A in <A>(array: ReadonlyArray<A>): Option.Option<A>
A
>):
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<
function (type parameter) A in <A>(array: ReadonlyArray<A>): Option.Option<A>
A
> =>
array: readonly A[]
array
.
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

@since2.0.0

@since2.0.0

Option
.
const some: <A>(value: A) => Option.Option<A>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(
array: readonly A[]
array
[0]) :
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <A>() => Option.Option<A>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
// 返回 Effect 的模拟获取函数
const
const fetchData: () => Effect.Effect<string, string>
fetchData
= ():
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
interface Effect<out A, out E = never, out R = never>

The Effect interface defines a value that describes a workflow or job, which can succeed or fail.

Details

The Effect interface represents a computation that can model a workflow involving various types of operations, such as synchronous, asynchronous, concurrent, and parallel interactions. It operates within a context of type R, and the result can either be a success with a value of type A or a failure with an error of type E. The Effect is designed to handle complex interactions with external resources, offering advanced features such as fiber-based concurrency, scheduling, interruption handling, and scalability. This makes it suitable for tasks that require fine-grained control over concurrency and error management.

To execute an Effect value, you need a Runtime, which provides the environment necessary to run and manage the computation.

@since2.0.0

@since2.0.0

Effect
<string, string> => {
const
const success: boolean
success
=
var Math: Math

An intrinsic object that provides basic mathematics functionality and constants.

Math
.
Math.random(): number

Returns a pseudorandom number between 0 and 1.

random
() > 0.5
return
const success: boolean
success
?
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <string>(value: string) => Effect.Effect<string, never, never>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

Example (Creating a Successful Effect)

import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@seefail to create an effect that represents a failure.

@since2.0.0

succeed
("some data")
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const fail: <string>(error: string) => Effect.Effect<never, string, never>

Creates an Effect that represents a recoverable error.

When to Use

Use this function to explicitly signal an error in an Effect. The error will keep propagating unless it is handled. You can handle the error with functions like

catchAll

or

catchTag

.

Example (Creating a Failed Effect)

import { Effect } from "effect"
// ┌─── Effect<never, Error, never>
// ▼
const failure = Effect.fail(
new Error("Operation failed due to network error")
)

@seesucceed to create an effect that represents a successful value.

@since2.0.0

fail
("Failed to fetch data")
}
// 混合 Option 和 Effect
const
const program: Effect.Effect<[number, string], string | NoSuchElementException, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const all: <readonly [Option.Option<number>, Effect.Effect<string, string, never>], NoExcessProperties<{
readonly concurrency?: Concurrency | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly discard?: boolean | undefined;
readonly mode?: "default" | "validate" | "either" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}, unknown>>(arg: readonly [Option.Option<number>, Effect.Effect<string, string, never>], options?: NoExcessProperties<{
readonly concurrency?: Concurrency | undefined;
readonly batching?: boolean | "inherit" | undefined;
readonly discard?: boolean | undefined;
readonly mode?: "default" | "validate" | "either" | undefined;
readonly concurrentFinalizers?: boolean | undefined;
}, unknown> | undefined) => Effect.Effect<...>

Combines multiple effects into one, returning results based on the input structure.

Details

Use this function when you need to run multiple effects and combine their results into a single output. It supports tuples, iterables, structs, and records, making it flexible for different input types.

For instance, if the input is a tuple:

// ┌─── a tuple of effects
// ▼
Effect.all([effect1, effect2, ...])

the effects are executed sequentially, and the result is a new effect containing the results as a tuple. The results in the tuple match the order of the effects passed to Effect.all.

Concurrency

You can control the execution order (e.g., sequential vs. concurrent) using the concurrency option.

Short-Circuiting Behavior

This function stops execution on the first error it encounters, this is called "short-circuiting". If any effect in the collection fails, the remaining effects will not run, and the error will be propagated. To change this behavior, you can use the mode option, which allows all effects to run and collect results as Either or Option.

The mode option

The { mode: "either" } option changes the behavior of Effect.all to ensure all effects run, even if some fail. Instead of stopping on the first failure, this mode collects both successes and failures, returning an array of Either instances where each result is either a Right (success) or a Left (failure).

Similarly, the { mode: "validate" } option uses Option to indicate success or failure. Each effect returns None for success and Some with the error for failure.

Example (Combining Effects in Tuples)

import { Effect, Console } from "effect"
const tupleOfEffects = [
Effect.succeed(42).pipe(Effect.tap(Console.log)),
Effect.succeed("Hello").pipe(Effect.tap(Console.log))
] as const
// ┌─── Effect<[number, string], never, never>
// ▼
const resultsAsTuple = Effect.all(tupleOfEffects)
Effect.runPromise(resultsAsTuple).then(console.log)
// Output:
// 42
// Hello
// [ 42, 'Hello' ]

Example (Combining Effects in Iterables)

import { Effect, Console } from "effect"
const iterableOfEffects: Iterable<Effect.Effect<number>> = [1, 2, 3].map(
(n) => Effect.succeed(n).pipe(Effect.tap(Console.log))
)
// ┌─── Effect<number[], never, never>
// ▼
const resultsAsArray = Effect.all(iterableOfEffects)
Effect.runPromise(resultsAsArray).then(console.log)
// Output:
// 1
// 2
// 3
// [ 1, 2, 3 ]

Example (Combining Effects in Structs)

import { Effect, Console } from "effect"
const structOfEffects = {
a: Effect.succeed(42).pipe(Effect.tap(Console.log)),
b: Effect.succeed("Hello").pipe(Effect.tap(Console.log))
}
// ┌─── Effect<{ a: number; b: string; }, never, never>
// ▼
const resultsAsStruct = Effect.all(structOfEffects)
Effect.runPromise(resultsAsStruct).then(console.log)
// Output:
// 42
// Hello
// { a: 42, b: 'Hello' }

Example (Combining Effects in Records)

import { Effect, Console } from "effect"
const recordOfEffects: Record<string, Effect.Effect<number>> = {
key1: Effect.succeed(1).pipe(Effect.tap(Console.log)),
key2: Effect.succeed(2).pipe(Effect.tap(Console.log))
}
// ┌─── Effect<{ [x: string]: number; }, never, never>
// ▼
const resultsAsRecord = Effect.all(recordOfEffects)
Effect.runPromise(resultsAsRecord).then(console.log)
// Output:
// 1
// 2
// { key1: 1, key2: 2 }

Example (Short-Circuiting Behavior)

import { Effect, Console } from "effect"
const program = Effect.all([
Effect.succeed("Task1").pipe(Effect.tap(Console.log)),
Effect.fail("Task2: Oh no!").pipe(Effect.tap(Console.log)),
// Won't execute due to earlier failure
Effect.succeed("Task3").pipe(Effect.tap(Console.log))
])
Effect.runPromiseExit(program).then(console.log)
// Output:
// Task1
// {
// _id: 'Exit',
// _tag: 'Failure',
// cause: { _id: 'Cause', _tag: 'Fail', failure: 'Task2: Oh no!' }
// }

Example (Collecting Results with mode: "either")

import { Effect, Console } from "effect"
const effects = [
Effect.succeed("Task1").pipe(Effect.tap(Console.log)),
Effect.fail("Task2: Oh no!").pipe(Effect.tap(Console.log)),
Effect.succeed("Task3").pipe(Effect.tap(Console.log))
]
const program = Effect.all(effects, { mode: "either" })
Effect.runPromiseExit(program).then(console.log)
// Output:
// Task1
// Task3
// {
// _id: 'Exit',
// _tag: 'Success',
// value: [
// { _id: 'Either', _tag: 'Right', right: 'Task1' },
// { _id: 'Either', _tag: 'Left', left: 'Task2: Oh no!' },
// { _id: 'Either', _tag: 'Right', right: 'Task3' }
// ]
// }

Example (Collecting Results with mode: "validate")

import { Effect, Console } from "effect"
const effects = [
Effect.succeed("Task1").pipe(Effect.tap(Console.log)),
Effect.fail("Task2: Oh no!").pipe(Effect.tap(Console.log)),
Effect.succeed("Task3").pipe(Effect.tap(Console.log))
]
const program = Effect.all(effects, { mode: "validate" })
Effect.runPromiseExit(program).then((result) => console.log("%o", result))
// Output:
// Task1
// Task3
// {
// _id: 'Exit',
// _tag: 'Failure',
// cause: {
// _id: 'Cause',
// _tag: 'Fail',
// failure: [
// { _id: 'Option', _tag: 'None' },
// { _id: 'Option', _tag: 'Some', value: 'Task2: Oh no!' },
// { _id: 'Option', _tag: 'None' }
// ]
// }
// }

@seeforEach for iterating over elements and applying an effect.

@seeallWith for a data-last version of this function.

@since2.0.0

all
([
const head: <number>(array: readonly number[]) => Option.Option<number>
head
([1, 2, 3]),
const fetchData: () => Effect.Effect<string, string>
fetchData
()])
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <[number, string], string | NoSuchElementException>(effect: Effect.Effect<[number, string], string | NoSuchElementException, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<[number, string]>

Executes an effect and returns the result as a Promise.

Details

This function runs an effect and converts its result into a Promise. If the effect succeeds, the Promise will resolve with the successful result. If the effect fails, the Promise will reject with an error, which includes the failure details of the effect.

The optional options parameter allows you to pass an AbortSignal for cancellation, enabling more fine-grained control over asynchronous tasks.

When to Use

Use this function when you need to execute an effect and work with its result in a promise-based system, such as when integrating with third-party libraries that expect Promise results.

Example (Running a Successful Effect as a Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.succeed(1)).then(console.log)
// Output: 1

Example (Handling a Failing Effect as a Rejected Promise)

import { Effect } from "effect"
Effect.runPromise(Effect.fail("my error")).catch(console.error)
// Output:
// (FiberFailure) Error: my error

@seerunPromiseExit for a version that returns an Exit type instead of rejecting.

@since2.0.0

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

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

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
(
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
)
/*
示例输出:
[ 1, 'some data' ]
*/

Option.zipWith 函数允许您使用提供的函数组合两个 Option 值。它创建一个新的 Option,保存两个原始 Option 值的组合值。

示例(将两个 Options 组合成一个对象)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const maybeName: Option.Option<string>
maybeName
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string> =
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("John")
const
const maybeAge: Option.Option<number>
maybeAge
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<number> =
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(25)
// 将姓名和年龄组合成一个人员对象
const
const person: Option.Option<{
name: string;
age: number;
}>
person
=
import Option

@since2.0.0

@since2.0.0

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)

Combines two Option values into a new Option by applying a provided function to their values.

Details

This function takes two Option values (self and that) and a combining function f. If both Option values are Some, the function f is applied to their values, and the result is wrapped in a new Some. If either Option is None, the result is None.

This utility is useful for combining two optional computations into a single result while maintaining type safety and avoiding explicit checks for None.

@example

import { Option } from "effect"
const maybeName: Option.Option<string> = Option.some("John")
const maybeAge: Option.Option<number> = Option.some(25)
// Combine the name and age into a person object
const person = Option.zipWith(maybeName, maybeAge, (name, age) => ({
name: name.toUpperCase(),
age
}))
console.log(person)
// Output:
// { _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }

@since2.0.0

zipWith
(
const maybeName: Option.Option<string>
maybeName
,
const maybeAge: Option.Option<number>
maybeAge
, (
name: string
name
,
age: number
age
) => ({
name: string
name
:
name: string
name
.
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
(),
age: number
age
}))
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const person: Option.Option<{
name: string;
age: number;
}>
person
)
/*
输出:
{ _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }
*/

如果任一 Option 值是 None,结果将是 None

示例(处理 None 值)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const maybeName: Option.Option<string>
maybeName
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string> =
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("John")
const
const maybeAge: Option.Option<number>
maybeAge
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<number> =
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <number>() => Option.Option<number>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
// 由于 maybeAge 是 None,结果也将是 None
const
const person: Option.Option<{
name: string;
age: number;
}>
person
=
import Option

@since2.0.0

@since2.0.0

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)

Combines two Option values into a new Option by applying a provided function to their values.

Details

This function takes two Option values (self and that) and a combining function f. If both Option values are Some, the function f is applied to their values, and the result is wrapped in a new Some. If either Option is None, the result is None.

This utility is useful for combining two optional computations into a single result while maintaining type safety and avoiding explicit checks for None.

@example

import { Option } from "effect"
const maybeName: Option.Option<string> = Option.some("John")
const maybeAge: Option.Option<number> = Option.some(25)
// Combine the name and age into a person object
const person = Option.zipWith(maybeName, maybeAge, (name, age) => ({
name: name.toUpperCase(),
age
}))
console.log(person)
// Output:
// { _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }

@since2.0.0

zipWith
(
const maybeName: Option.Option<string>
maybeName
,
const maybeAge: Option.Option<number>
maybeAge
, (
name: string
name
,
age: number
age
) => ({
name: string
name
:
name: string
name
.
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
(),
age: number
age
}))
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const person: Option.Option<{
name: string;
age: number;
}>
person
)
// 输出: { _id: 'Option', _tag: 'None' }

要在不转换内容的情况下组合多个 Option 值,您可以使用 Option.all。此函数返回一个结构与输入匹配的 Option

  • 如果您传递一个元组,结果将是相同长度的元组。
  • 如果您传递一个结构体,结果将是具有相同键的结构体。
  • 如果您传递一个 Iterable,结果将是一个数组。

示例(将多个 Options 组合成元组和结构体)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const maybeName: Option.Option<string>
maybeName
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string> =
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("John")
const
const maybeAge: Option.Option<number>
maybeAge
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<number> =
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(25)
// ┌─── Option<[string, number]>
// ▼
const
const tuple: Option.Option<[string, number]>
tuple
=
import Option

@since2.0.0

@since2.0.0

Option
.
const all: <readonly [Option.Option<string>, Option.Option<number>]>(input: readonly [Option.Option<string>, Option.Option<number>]) => Option.Option<[string, number]>

Combines a structure of Options into a single Option containing the values with the same structure.

Details

This function takes a structure of Options (a tuple, struct, or iterable) and produces a single Option that contains the values from the input structure if all Options are Some. If any Option in the input is None, the result is None. The structure of the input is preserved in the output.

  • If the input is a tuple (e.g., an array), the result will be an Option containing a tuple with the same length.
  • If the input is a struct (e.g., an object), the result will be an Option containing a struct with the same keys.
  • If the input is an iterable, the result will be an Option containing an array.

@example

import { Option } from "effect"
const maybeName: Option.Option<string> = Option.some("John")
const maybeAge: Option.Option<number> = Option.some(25)
// ┌─── Option<[string, number]>
// ▼
const tuple = Option.all([maybeName, maybeAge])
console.log(tuple)
// Output:
// { _id: 'Option', _tag: 'Some', value: [ 'John', 25 ] }
// ┌─── Option<{ name: string; age: number; }>
// ▼
const struct = Option.all({ name: maybeName, age: maybeAge })
console.log(struct)
// Output:
// { _id: 'Option', _tag: 'Some', value: { name: 'John', age: 25 } }

@since2.0.0

all
([
const maybeName: Option.Option<string>
maybeName
,
const maybeAge: Option.Option<number>
maybeAge
])
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const tuple: Option.Option<[string, number]>
tuple
)
/*
输出:
{ _id: 'Option', _tag: 'Some', value: [ 'John', 25 ] }
*/
// ┌─── Option<{ name: string; age: number; }>
// ▼
const
const struct: Option.Option<{
name: string;
age: number;
}>
struct
=
import Option

@since2.0.0

@since2.0.0

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<{
name: string;
age: number;
}>

Combines a structure of Options into a single Option containing the values with the same structure.

Details

This function takes a structure of Options (a tuple, struct, or iterable) and produces a single Option that contains the values from the input structure if all Options are Some. If any Option in the input is None, the result is None. The structure of the input is preserved in the output.

  • If the input is a tuple (e.g., an array), the result will be an Option containing a tuple with the same length.
  • If the input is a struct (e.g., an object), the result will be an Option containing a struct with the same keys.
  • If the input is an iterable, the result will be an Option containing an array.

@example

import { Option } from "effect"
const maybeName: Option.Option<string> = Option.some("John")
const maybeAge: Option.Option<number> = Option.some(25)
// ┌─── Option<[string, number]>
// ▼
const tuple = Option.all([maybeName, maybeAge])
console.log(tuple)
// Output:
// { _id: 'Option', _tag: 'Some', value: [ 'John', 25 ] }
// ┌─── Option<{ name: string; age: number; }>
// ▼
const struct = Option.all({ name: maybeName, age: maybeAge })
console.log(struct)
// Output:
// { _id: 'Option', _tag: 'Some', value: { name: 'John', age: 25 } }

@since2.0.0

all
({
name: Option.Option<string>
name
:
const maybeName: Option.Option<string>
maybeName
,
age: Option.Option<number>
age
:
const maybeAge: Option.Option<number>
maybeAge
})
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const struct: Option.Option<{
name: string;
age: number;
}>
struct
)
/*
输出:
{ _id: 'Option', _tag: 'Some', value: { name: 'John', age: 25 } }
*/

如果任何 Option 值是 None,结果将是 None

示例

import { Option } from "effect"
const maybeName: Option.Option<string> = Option.some("John")
const maybeAge: Option.Option<number> = Option.none()
console.log(Option.all([maybeName, maybeAge]))
// 输出: { _id: 'Option', _tag: 'None' }

类似于 Effect.genOption.gen 提供了一种更可读的、基于生成器的语法来处理 Option 值,使涉及 Option 的代码更易于编写和理解。这种方法类似于使用 async/await,但专为 Option 量身定制。

示例(使用 Option.gen 创建组合值)

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const maybeName: Option.Option<string>
maybeName
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string> =
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <string>(value: string) => Option.Option<string>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
("John")
const
const maybeAge: Option.Option<number>
maybeAge
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<number> =
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(25)
const
const person: Option.Option<{
name: string;
age: number;
}>
person
=
import Option

@since2.0.0

@since2.0.0

Option
.
const gen: Gen
<unknown, YieldWrap<Option.None<string>> | YieldWrap<Option.Some<string>> | YieldWrap<Option.None<number>> | YieldWrap<Option.Some<number>>, {
name: string;
age: number;
}>(...args: [self: unknown, body: (this: unknown, resume: Adapter<Option.OptionTypeLambda>) => Generator<YieldWrap<Option.None<string>> | YieldWrap<Option.Some<string>> | YieldWrap<Option.None<number>> | YieldWrap<Option.Some<number>>, {
name: string;
age: number;
}, never>] | [body: ...]) => Option.Option<...>

Similar to Effect.gen, Option.gen provides a more readable, generator-based syntax for working with Option values, making code that involves Option easier to write and understand. This approach is similar to using async/await but tailored for Option.

Example (Using Option.gen to Create a Combined Value)

import { Option } from "effect"
const maybeName: Option.Option<string> = Option.some("John")
const maybeAge: Option.Option<number> = Option.some(25)
const person = Option.gen(function* () {
const name = (yield* maybeName).toUpperCase()
const age = yield* maybeAge
return { name, age }
})
console.log(person)
// Output:
// { _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }

@since2.0.0

gen
(function* () {
const
const name: string
name
= (yield*
const maybeName: Option.Option<string>
maybeName
).
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
()
const
const age: number
age
= yield*
const maybeAge: Option.Option<number>
maybeAge
return {
name: string
name
,
age: number
age
}
})
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const person: Option.Option<{
name: string;
age: number;
}>
person
)
/*
输出:
{ _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }
*/

当序列中的任何 Option 值是 None 时,生成器立即返回 None 值,跳过进一步的操作:

示例(使用 Option.gen 处理 None 值)

在此示例中,Option.gen 一旦遇到 None 值就会停止执行,有效地传播缺失值而不执行进一步的操作。

import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
const
const maybeName: Option.Option<string>
maybeName
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<string> =
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <string>() => Option.Option<string>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()
const
const maybeAge: Option.Option<number>
maybeAge
:
import Option

@since2.0.0

@since2.0.0

Option
.
type Option<A> = Option.None<A> | Option.Some<A>

The Option data type represents optional values. An Option<A> can either be Some<A>, containing a value of type A, or None, representing the absence of a value.

When to Use

You can use Option in scenarios like:

  • 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

@since2.0.0

@since2.0.0

Option
<number> =
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(25)
const
const program: Option.Option<{
name: string;
age: number;
}>
program
=
import Option

@since2.0.0

@since2.0.0

Option
.
const gen: Gen
<unknown, YieldWrap<Option.None<string>> | YieldWrap<Option.Some<string>> | YieldWrap<Option.None<number>> | YieldWrap<Option.Some<number>>, {
name: string;
age: number;
}>(...args: [self: unknown, body: (this: unknown, resume: Adapter<Option.OptionTypeLambda>) => Generator<YieldWrap<Option.None<string>> | YieldWrap<Option.Some<string>> | YieldWrap<Option.None<number>> | YieldWrap<Option.Some<number>>, {
name: string;
age: number;
}, never>] | [body: ...]) => Option.Option<...>

Similar to Effect.gen, Option.gen provides a more readable, generator-based syntax for working with Option values, making code that involves Option easier to write and understand. This approach is similar to using async/await but tailored for Option.

Example (Using Option.gen to Create a Combined Value)

import { Option } from "effect"
const maybeName: Option.Option<string> = Option.some("John")
const maybeAge: Option.Option<number> = Option.some(25)
const person = Option.gen(function* () {
const name = (yield* maybeName).toUpperCase()
const age = yield* maybeAge
return { name, age }
})
console.log(person)
// Output:
// { _id: 'Option', _tag: 'Some', value: { name: 'JOHN', age: 25 } }

@since2.0.0

gen
(function* () {
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
("正在获取姓名...")
const
const name: string
name
= (yield*
const maybeName: Option.Option<string>
maybeName
).
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
()
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
("正在获取年龄...")
const
const age: number
age
= yield*
const maybeAge: Option.Option<number>
maybeAge
return {
name: string
name
,
age: number
age
}
})
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const program: Option.Option<{
name: string;
age: number;
}>
program
)
/*
输出:
正在获取姓名...
{ _id: 'Option', _tag: 'None' }
*/

在这些示例中使用 console.log 仅用于演示目的。使用 Option.gen 时,避免在生成器函数中包含副作用,因为 Option 应该保持为纯数据结构。

您可以使用 Option.getEquivalence 函数比较 Option 值。此函数允许您通过为它们可能包含的值类型提供 Equivalence 来指定如何比较 Option 类型的内容。

示例(比较可选数字的等价性)

假设您有可选数字并想要检查它们是否等价。以下是如何使用 Option.getEquivalence

import {
import Option

@since2.0.0

@since2.0.0

Option
,
import Equivalence
Equivalence
} from "effect"
const
const myEquivalence: Equivalence.Equivalence<Option.Option<number>>
myEquivalence
=
import Option

@since2.0.0

@since2.0.0

Option
.
const getEquivalence: <number>(isEquivalent: Equivalence.Equivalence<number>) => Equivalence.Equivalence<Option.Option<number>>

Creates an Equivalence instance for comparing Option values, using a provided Equivalence for the inner type.

Details

This function takes an Equivalence instance for a specific type A and produces an Equivalence instance for Option<A>. The resulting Equivalence determines whether two Option values are equivalent:

  • Two Nones are considered equivalent.
  • A Some and a None are not equivalent.
  • Two Some values are equivalent if their inner values are equivalent according to the provided Equivalence.

Example (Comparing Optional Numbers for Equivalence)

import { Number, Option } from "effect"
const isEquivalent = Option.getEquivalence(Number.Equivalence)
console.log(isEquivalent(Option.none(), Option.none()))
// Output: true
console.log(isEquivalent(Option.none(), Option.some(1)))
// Output: false
console.log(isEquivalent(Option.some(1), Option.none()))
// Output: false
console.log(isEquivalent(Option.some(1), Option.some(2)))
// Output: false
console.log(isEquivalent(Option.some(1), Option.some(1)))
// Output: true

@since2.0.0

getEquivalence
(
import Equivalence
Equivalence
.
const number: Equivalence.Equivalence<number>

@since2.0.0

number
)
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const myEquivalence: Equivalence.Equivalence
(self: Option.Option<number>, that: Option.Option<number>) => boolean
myEquivalence
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(1),
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(1)))
// 输出: true,两个选项都包含数字 1
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const myEquivalence: Equivalence.Equivalence
(self: Option.Option<number>, that: Option.Option<number>) => boolean
myEquivalence
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(1),
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(2)))
// 输出: false,数字不同
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

log
(
const myEquivalence: Equivalence.Equivalence
(self: Option.Option<number>, that: Option.Option<number>) => boolean
myEquivalence
(
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(1),
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <number>() => Option.Option<number>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
()))
// 输出: false,一个是数字,另一个为空

您可以使用 Option.getOrder 函数对 Option 值的集合进行排序。此函数有助于为 Option 中包含的值类型指定自定义排序规则。

示例(排序可选数字)

假设您有一个可选数字列表,并希望按升序排序,将空值(Option.none())视为最低值:

import {
import Option

@since2.0.0

@since2.0.0

Option
,
import Array
Array
,
import Order
Order
} from "effect"
const
const items: (Option.None<number> | Option.Some<number>)[]
items
= [
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(1),
import Option

@since2.0.0

@since2.0.0

Option
.
const none: <never>() => Option.Option<never>

Represents the absence of a value by creating an empty Option.

Option.none returns an Option<never>, which is a subtype of Option<A>. This means you can use it in place of any Option<A> regardless of the type A.

Example (Creating an Option with No Value)

import { Option } from "effect"
// An Option holding no value
//
// ┌─── Option<never>
// ▼
const noValue = Option.none()
console.log(noValue)
// Output: { _id: 'Option', _tag: 'None' }

@seesome for the opposite operation.

@since2.0.0

none
(),
import Option

@since2.0.0

@since2.0.0

Option
.
const some: <number>(value: number) => Option.Option<number>

Wraps the given value into an Option to represent its presence.

Example (Creating an Option with a Value)

import { Option } from "effect"
// An Option holding the number 1
//
// ┌─── Option<number>
// ▼
const value = Option.some(1)
console.log(value)
// Output: { _id: 'Option', _tag: 'Some', value: 1 }

@seenone for the opposite operation.

@since2.0.0

some
(2)]
// 创建用于排序包含数字的 Option 值的顺序
const
const myOrder: Order.Order<Option.Option<number>>
myOrder
=
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrder: <number>(O: Order.Order<number>) => Order.Order<Option.Option<number>>

Creates an Order instance for comparing Option values, using a provided Order for the inner type.

Details

This function produces an Order instance for Option<A>, allowing Option values to be compared:

  • None is always considered less than any Some value.
  • If both are Some, their inner values are compared using the provided Order instance.

@example

import { Number, Option } from "effect"
const order = Option.getOrder(Number.Order)
console.log(order(Option.none(), Option.none()))
// Output: 0
console.log(order(Option.none(), Option.some(1)))
// Output: -1
console.log(order(Option.some(1), Option.none()))
// Output: 1
console.log(order(Option.some(1), Option.some(2)))
// Output: -1
console.log(order(Option.some(1), Option.some(1)))
// Output: 0

@since2.0.0

getOrder
(
import Order
Order
.
const number: Order.Order<number>

@since2.0.0

number
)
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 and process.stderr. 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 for more information.

Example using the global console:

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:

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

@seesource

console
.
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) (the arguments are all passed to util.format()).

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() for more information.

@sincev0.1.100

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.

@since2.0.0

sort
(
const myOrder: Order.Order<Option.Option<number>>
myOrder
)(
const items: (Option.None<number> | Option.Some<number>)[]
items
))
/*
输出:
[
{ _id: 'Option', _tag: 'None' }, // None 首先出现,因为它被认为是最低的
{ _id: 'Option', _tag: 'Some', value: 1 }, // 按升序排序
{ _id: 'Option', _tag: 'Some', value: 2 }
]
*/

示例(按逆序排序可选日期)

考虑一个更复杂的情况,您有一个包含可选日期的对象列表,并希望按降序排序,将 Option.none() 值放在末尾:

import { Option, Array, Order } from "effect"
const items = [
{ data: Option.some(new Date(10)) },
{ data: Option.some(new Date(20)) },
{ data: Option.none() }
]
// 定义在 Option 值内按逆序排序日期的顺序
const sorted = Array.sortWith(
items,
(item) => item.data,
Order.reverse(Option.getOrder(Order.Date))
)
console.log(sorted)
/*
输出:
[
{ data: { _id: 'Option', _tag: 'Some', value: '1970-01-01T00:00:00.020Z' } },
{ data: { _id: 'Option', _tag: 'Some', value: '1970-01-01T00:00:00.010Z' } },
{ data: { _id: 'Option', _tag: 'None' } } // None 放在最后
]
*/