Skip to content

Data

Data 模块简化了在 TypeScript 中创建和处理数据结构。它提供了定义数据类型、确保对象之间相等性以及哈希数据以进行高效比较的工具。

Data 模块提供了用于创建数据类型的构造函数,内置支持相等性和哈希,无需自定义实现。

这意味着使用这些构造函数创建的两个值如果具有相同的结构和值,则被认为是相等的。

在普通 JavaScript 中,只有当对象引用完全相同的实例时,才被认为是相等的。

示例(在普通 JavaScript 中比较两个对象)

const
const alice: {
name: string;
age: number;
}
alice
= {
name: string
name
: "Alice",
age: number
age
: 30 }
// 此比较为 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 alice: {
name: string;
age: number;
}
alice
=== {
name: string
name
: "Alice",
age: number
age
: 30 }) // 输出: false
Error ts(2839) ― This condition will always return 'false' since JavaScript compares objects by reference, not value.

然而,Data.struct 构造函数允许您基于结构和内容比较值。

示例(创建和检查结构体的相等性)

import {
import Data
Data
,
import Equal
Equal
} from "effect"
// ┌─── { readonly name: string; readonly age: number; }
// ▼
const
const alice: {
readonly name: string;
readonly age: number;
}
alice
=
import Data
Data
.
const struct: <{
name: string;
age: number;
}>(a: {
name: string;
age: number;
}) => {
readonly name: string;
readonly age: number;
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
name: string
name
: "Alice",
age: number
age
: 30 })
// 检查 Alice 是否等于具有相同结构和值的新对象
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 Equal
Equal
.
function equals<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(self: {
readonly name: string;
readonly age: number;
}, that: {
readonly name: string;
readonly age: number;
}): boolean (+1 overload)

@since2.0.0

equals
(
const alice: {
readonly name: string;
readonly age: number;
}
alice
,
import Data
Data
.
const struct: <{
name: string;
age: number;
}>(a: {
name: string;
age: number;
}) => {
readonly name: string;
readonly age: number;
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
name: string
name
: "Alice",
age: number
age
: 30 })))
// 输出: true
// 检查 Alice 是否等于具有相同内容的普通 JavaScript 对象
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 Equal
Equal
.
function equals<{
readonly name: string;
readonly age: number;
}, {
name: string;
age: number;
}>(self: {
readonly name: string;
readonly age: number;
}, that: {
name: string;
age: number;
}): boolean (+1 overload)

@since2.0.0

equals
(
const alice: {
readonly name: string;
readonly age: number;
}
alice
, {
name: string
name
: "Alice",
age: number
age
: 30 }))
// 输出: false

Equal.equals 执行的比较是浅层的,意味着嵌套对象不会递归比较,除非它们也使用 Data.struct 创建。

示例(嵌套对象的浅层比较)

import {
import Data
Data
,
import Equal
Equal
} from "effect"
const
const nested: {
readonly name: string;
readonly nested_field: {
value: number;
};
}
nested
=
import Data
Data
.
const struct: <{
name: string;
nested_field: {
value: number;
};
}>(a: {
name: string;
nested_field: {
value: number;
};
}) => {
readonly name: string;
readonly nested_field: {
value: number;
};
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
name: string
name
: "Alice",
nested_field: {
value: number;
}
nested_field
: {
value: number
value
: 42 } })
// 这将为 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
(
import Equal
Equal
.
function equals<{
readonly name: string;
readonly nested_field: {
value: number;
};
}, {
readonly name: string;
readonly nested_field: {
value: number;
};
}>(self: {
readonly name: string;
readonly nested_field: {
value: number;
};
}, that: {
readonly name: string;
readonly nested_field: {
value: number;
};
}): boolean (+1 overload)

@since2.0.0

equals
(
const nested: {
readonly name: string;
readonly nested_field: {
value: number;
};
}
nested
,
import Data
Data
.
const struct: <{
name: string;
nested_field: {
value: number;
};
}>(a: {
name: string;
nested_field: {
value: number;
};
}) => {
readonly name: string;
readonly nested_field: {
value: number;
};
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
name: string
name
: "Alice",
nested_field: {
value: number;
}
nested_field
: {
value: number
value
: 42 } })
)
)
// 输出: false

要确保嵌套对象按结构比较,也要对它们使用 Data.struct

示例(正确比较嵌套对象)

import {
import Data
Data
,
import Equal
Equal
} from "effect"
const
const nested: {
readonly name: string;
readonly nested_field: {
readonly value: number;
};
}
nested
=
import Data
Data
.
const struct: <{
name: string;
nested_field: {
readonly value: number;
};
}>(a: {
name: string;
nested_field: {
readonly value: number;
};
}) => {
readonly name: string;
readonly nested_field: {
readonly value: number;
};
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
name: string
name
: "Alice",
nested_field: {
readonly value: number;
}
nested_field
:
import Data
Data
.
const struct: <{
value: number;
}>(a: {
value: number;
}) => {
readonly value: number;
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
value: number
value
: 42 })
})
// 现在,比较返回 true
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 Equal
Equal
.
function equals<{
readonly name: string;
readonly nested_field: {
readonly value: number;
};
}, {
readonly name: string;
readonly nested_field: {
readonly value: number;
};
}>(self: {
readonly name: string;
readonly nested_field: {
readonly value: number;
};
}, that: {
readonly name: string;
readonly nested_field: {
readonly value: number;
};
}): boolean (+1 overload)

@since2.0.0

equals
(
const nested: {
readonly name: string;
readonly nested_field: {
readonly value: number;
};
}
nested
,
import Data
Data
.
const struct: <{
name: string;
nested_field: {
readonly value: number;
};
}>(a: {
name: string;
nested_field: {
readonly value: number;
};
}) => {
readonly name: string;
readonly nested_field: {
readonly value: number;
};
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
name: string
name
: "Alice",
nested_field: {
readonly value: number;
}
nested_field
:
import Data
Data
.
const struct: <{
value: number;
}>(a: {
value: number;
}) => {
readonly value: number;
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
value: number
value
: 42 })
})
)
)
// 输出: true

要使用元组表示数据,您可以使用 Data.tuple 构造函数。这确保您的元组可以进行结构比较。

示例(创建和检查元组的相等性)

import {
import Data
Data
,
import Equal
Equal
} from "effect"
// ┌─── readonly [string, number]
// ▼
const
const alice: readonly [string, number]
alice
=
import Data
Data
.
const tuple: <[string, number]>(as_0: string, as_1: number) => readonly [string, number]

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.tuple("Alice", 30)
const bob = Data.tuple("Bob", 40)
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.tuple("Alice", 30)), true)
assert.deepStrictEqual(Equal.equals(alice, ["Alice", 30]), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

tuple
("Alice", 30)
// 检查 Alice 是否等于具有相同结构和值的新元组
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 Equal
Equal
.
function equals<readonly [string, number], readonly [string, number]>(self: readonly [string, number], that: readonly [string, number]): boolean (+1 overload)

@since2.0.0

equals
(
const alice: readonly [string, number]
alice
,
import Data
Data
.
const tuple: <[string, number]>(as_0: string, as_1: number) => readonly [string, number]

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.tuple("Alice", 30)
const bob = Data.tuple("Bob", 40)
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.tuple("Alice", 30)), true)
assert.deepStrictEqual(Equal.equals(alice, ["Alice", 30]), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

tuple
("Alice", 30)))
// 输出: true
// 检查 Alice 是否等于具有相同内容的普通 JavaScript 元组
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 Equal
Equal
.
function equals<readonly [string, number], (string | number)[]>(self: readonly [string, number], that: (string | number)[]): boolean (+1 overload)

@since2.0.0

equals
(
const alice: readonly [string, number]
alice
, ["Alice", 30]))
// 输出: false

您可以使用 Data.array 创建支持结构相等性的类数组数据结构。

示例(创建和检查数组的相等性)

import {
import Data
Data
,
import Equal
Equal
} from "effect"
// ┌─── readonly number[]
// ▼
const
const numbers: readonly number[]
numbers
=
import Data
Data
.
const array: <number[]>(as: number[]) => readonly number[]

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
const persons = Data.array([alice, bob])
assert.deepStrictEqual(
Equal.equals(
persons,
Data.array([
Data.struct({ name: "Alice", age: 30 }),
Data.struct({ name: "Bob", age: 40 })
])
),
true
)

@since2.0.0

array
([1, 2, 3, 4, 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 Equal
Equal
.
function equals<readonly number[], readonly number[]>(self: readonly number[], that: readonly number[]): boolean (+1 overload)

@since2.0.0

equals
(
const numbers: readonly number[]
numbers
,
import Data
Data
.
const array: <number[]>(as: number[]) => readonly number[]

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
const persons = Data.array([alice, bob])
assert.deepStrictEqual(
Equal.equals(
persons,
Data.array([
Data.struct({ name: "Alice", age: 30 }),
Data.struct({ name: "Bob", age: 40 })
])
),
true
)

@since2.0.0

array
([1, 2, 3, 4, 5])))
// 输出: true
// 检查数组是否等于具有相同内容的普通 JavaScript 数组
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 Equal
Equal
.
function equals<readonly number[], number[]>(self: readonly number[], that: number[]): boolean (+1 overload)

@since2.0.0

equals
(
const numbers: readonly number[]
numbers
, [1, 2, 3, 4, 5]))
// 输出: false

该模块引入了一个称为”Case 类”的概念,它在定义数据类型时自动化各种基本操作。 这些操作包括生成构造函数、处理相等性检查和管理哈希

Case 类可以通过两种主要方式定义:

  • 使用 casetagged 作为普通对象
  • 使用 ClassTaggedClass 作为 TypeScript 类

Data.case 助手为您的数据类型生成构造函数和内置的相等性检查和哈希支持。

示例(定义 Case 类并检查相等性)

在此示例中,Data.case 用于为 Person 创建构造函数。生成的实例具有内置的相等性检查支持,允许您使用 Equal.equals 直接比较它们。

import {
import Data
Data
,
import Equal
Equal
} from "effect"
interface
interface Person
Person
{
readonly
Person.name: string
name
: string
}
// 为 `Person` 创建构造函数
//
// ┌─── (args: { readonly name: string; }) => Person
// ▼
const
const make: Data.Case.Constructor<Person, never>
make
=
import Data
Data
.
case<Person>(): Data.Case.Constructor<Person, never>
export case

Provides a constructor for the specified Case.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
interface Person {
readonly name: string
}
// Creating a constructor for the specified Case
const Person = Data.case<Person>()
// Creating instances of Person
const mike1 = Person({ name: "Mike" })
const mike2 = Person({ name: "Mike" })
const john = Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

case
<
interface Person
Person
>()
const
const alice: Person
alice
=
const make: Data.Case.Constructor
(args: {
readonly name: string;
}) => Person
make
({
name: string
name
: "Alice" })
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 Equal
Equal
.
function equals<Person, Person>(self: Person, that: Person): boolean (+1 overload)

@since2.0.0

equals
(
const alice: Person
alice
,
const make: Data.Case.Constructor
(args: {
readonly name: string;
}) => Person
make
({
name: string
name
: "Alice" })))
// 输出: true
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 Equal
Equal
.
function equals<Person, Person>(self: Person, that: Person): boolean (+1 overload)

@since2.0.0

equals
(
const alice: Person
alice
,
const make: Data.Case.Constructor
(args: {
readonly name: string;
}) => Person
make
({
name: string
name
: "John" })))
// 输出: false

示例(定义和比较嵌套 Case 类)

此示例演示了使用 Data.case 创建嵌套数据结构,例如包含 AddressPerson 类型。PersonAddress 构造函数都支持相等性检查。

import {
import Data
Data
,
import Equal
Equal
} from "effect"
interface
interface Address
Address
{
readonly
Address.street: string
street
: string
readonly
Address.city: string
city
: string
}
// 为 `Address` 创建构造函数
const
const Address: Data.Case.Constructor<Address, never>
Address
=
import Data
Data
.
case<Address>(): Data.Case.Constructor<Address, never>
export case

Provides a constructor for the specified Case.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
interface Person {
readonly name: string
}
// Creating a constructor for the specified Case
const Person = Data.case<Person>()
// Creating instances of Person
const mike1 = Person({ name: "Mike" })
const mike2 = Person({ name: "Mike" })
const john = Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

case
<
interface Address
Address
>()
interface
interface Person
Person
{
readonly
Person.name: string
name
: string
readonly
Person.address: Address
address
:
interface Address
Address
}
// 为 `Person` 创建构造函数
const
const Person: Data.Case.Constructor<Person, never>
Person
=
import Data
Data
.
case<Person>(): Data.Case.Constructor<Person, never>
export case

Provides a constructor for the specified Case.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
interface Person {
readonly name: string
}
// Creating a constructor for the specified Case
const Person = Data.case<Person>()
// Creating instances of Person
const mike1 = Person({ name: "Mike" })
const mike2 = Person({ name: "Mike" })
const john = Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

case
<
interface Person
Person
>()
const
const alice: Person
alice
=
const Person: Data.Case.Constructor
(args: {
readonly name: string;
readonly address: Address;
}) => Person
Person
({
name: string
name
: "Alice",
address: Address
address
:
const Address: Data.Case.Constructor
(args: {
readonly street: string;
readonly city: string;
}) => Address
Address
({
street: string
street
: "123 Main St",
city: string
city
: "Wonderland" })
})
const
const anotherAlice: Person
anotherAlice
=
const Person: Data.Case.Constructor
(args: {
readonly name: string;
readonly address: Address;
}) => Person
Person
({
name: string
name
: "Alice",
address: Address
address
:
const Address: Data.Case.Constructor
(args: {
readonly street: string;
readonly city: string;
}) => Address
Address
({
street: string
street
: "123 Main St",
city: string
city
: "Wonderland" })
})
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 Equal
Equal
.
function equals<Person, Person>(self: Person, that: Person): boolean (+1 overload)

@since2.0.0

equals
(
const alice: Person
alice
,
const anotherAlice: Person
anotherAlice
))
// 输出: true

或者,您可以使用 Data.struct 创建嵌套数据结构,而无需定义单独的 Address 构造函数。

示例(对嵌套对象使用 Data.struct

import {
import Data
Data
,
import Equal
Equal
} from "effect"
interface
interface Person
Person
{
readonly
Person.name: string
name
: string
readonly
Person.address: {
readonly street: string;
readonly city: string;
}
address
: {
readonly
street: string
street
: string
readonly
city: string
city
: string
}
}
// 为 `Person` 创建构造函数
const
const Person: Data.Case.Constructor<Person, never>
Person
=
import Data
Data
.
case<Person>(): Data.Case.Constructor<Person, never>
export case

Provides a constructor for the specified Case.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
interface Person {
readonly name: string
}
// Creating a constructor for the specified Case
const Person = Data.case<Person>()
// Creating instances of Person
const mike1 = Person({ name: "Mike" })
const mike2 = Person({ name: "Mike" })
const john = Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

case
<
interface Person
Person
>()
const
const alice: Person
alice
=
const Person: Data.Case.Constructor
(args: {
readonly name: string;
readonly address: {
readonly street: string;
readonly city: string;
};
}) => Person
Person
({
name: string
name
: "Alice",
address: {
readonly street: string;
readonly city: string;
}
address
:
import Data
Data
.
const struct: <{
street: string;
city: string;
}>(a: {
street: string;
city: string;
}) => {
readonly street: string;
readonly city: string;
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
street: string
street
: "123 Main St",
city: string
city
: "Wonderland" })
})
const
const anotherAlice: Person
anotherAlice
=
const Person: Data.Case.Constructor
(args: {
readonly name: string;
readonly address: {
readonly street: string;
readonly city: string;
};
}) => Person
Person
({
name: string
name
: "Alice",
address: {
readonly street: string;
readonly city: string;
}
address
:
import Data
Data
.
const struct: <{
street: string;
city: string;
}>(a: {
street: string;
city: string;
}) => {
readonly street: string;
readonly city: string;
}

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
const alice = Data.struct({ name: "Alice", age: 30 })
const bob = Data.struct({ name: "Bob", age: 40 })
assert.deepStrictEqual(Equal.equals(alice, alice), true)
assert.deepStrictEqual(Equal.equals(alice, Data.struct({ name: "Alice", age: 30 })), true)
assert.deepStrictEqual(Equal.equals(alice, { name: "Alice", age: 30 }), false)
assert.deepStrictEqual(Equal.equals(alice, bob), false)

@since2.0.0

struct
({
street: string
street
: "123 Main St",
city: string
city
: "Wonderland" })
})
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 Equal
Equal
.
function equals<Person, Person>(self: Person, that: Person): boolean (+1 overload)

@since2.0.0

equals
(
const alice: Person
alice
,
const anotherAlice: Person
anotherAlice
))
// 输出: true

示例(定义和比较递归 Case 类)

此示例演示了使用 Data.case 定义二叉树的递归结构,其中每个节点可以包含其他节点。

import {
import Data
Data
,
import Equal
Equal
} from "effect"
interface
interface BinaryTree<T>
BinaryTree
<
function (type parameter) T in BinaryTree<T>
T
> {
readonly
BinaryTree<T>.value: T
value
:
function (type parameter) T in BinaryTree<T>
T
readonly
BinaryTree<T>.left: BinaryTree<T> | null
left
:
interface BinaryTree<T>
BinaryTree
<
function (type parameter) T in BinaryTree<T>
T
> | null
readonly
BinaryTree<T>.right: BinaryTree<T> | null
right
:
interface BinaryTree<T>
BinaryTree
<
function (type parameter) T in BinaryTree<T>
T
> | null
}
// 为 `BinaryTree` 创建构造函数
const
const BinaryTree: Data.Case.Constructor<BinaryTree<number>, never>
BinaryTree
=
import Data
Data
.
case<BinaryTree<number>>(): Data.Case.Constructor<BinaryTree<number>, never>
export case

Provides a constructor for the specified Case.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
interface Person {
readonly name: string
}
// Creating a constructor for the specified Case
const Person = Data.case<Person>()
// Creating instances of Person
const mike1 = Person({ name: "Mike" })
const mike2 = Person({ name: "Mike" })
const john = Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

case
<
interface BinaryTree<T>
BinaryTree
<number>>()
const
const tree1: BinaryTree<number>
tree1
=
const BinaryTree: Data.Case.Constructor
(args: {
readonly value: number;
readonly left: BinaryTree<number> | null;
readonly right: BinaryTree<number> | null;
}) => BinaryTree<number>
BinaryTree
({
value: number
value
: 0,
left: BinaryTree<number> | null
left
:
const BinaryTree: Data.Case.Constructor
(args: {
readonly value: number;
readonly left: BinaryTree<number> | null;
readonly right: BinaryTree<number> | null;
}) => BinaryTree<number>
BinaryTree
({
value: number
value
: 1,
left: BinaryTree<number> | null
left
: null,
right: BinaryTree<number> | null
right
: null }),
right: BinaryTree<number> | null
right
: null
})
const
const tree2: BinaryTree<number>
tree2
=
const BinaryTree: Data.Case.Constructor
(args: {
readonly value: number;
readonly left: BinaryTree<number> | null;
readonly right: BinaryTree<number> | null;
}) => BinaryTree<number>
BinaryTree
({
value: number
value
: 0,
left: BinaryTree<number> | null
left
:
const BinaryTree: Data.Case.Constructor
(args: {
readonly value: number;
readonly left: BinaryTree<number> | null;
readonly right: BinaryTree<number> | null;
}) => BinaryTree<number>
BinaryTree
({
value: number
value
: 1,
left: BinaryTree<number> | null
left
: null,
right: BinaryTree<number> | null
right
: null }),
right: BinaryTree<number> | null
right
: 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 Equal
Equal
.
function equals<BinaryTree<number>, BinaryTree<number>>(self: BinaryTree<number>, that: BinaryTree<number>): boolean (+1 overload)

@since2.0.0

equals
(
const tree1: BinaryTree<number>
tree1
,
const tree2: BinaryTree<number>
tree2
))
// 输出: true

当您使用包含标签字段的数据类型时,如在不相交联合类型中,为每个实例手动定义标签可能会变得重复。使用 case 方法需要您每次都指定标签字段,这可能很麻烦。

示例(手动定义标记 Case 类)

在这里,我们使用 Data.case 创建带有 _tag 字段的 Person 类型。请注意,每个新实例都需要指定 _tag

import {
import Data
Data
} from "effect"
interface
interface Person
Person
{
readonly
Person._tag: "Person"
_tag
: "Person" // the tag
readonly
Person.name: string
name
: string
}
const
const Person: Data.Case.Constructor<Person, never>
Person
=
import Data
Data
.
case<Person>(): Data.Case.Constructor<Person, never>
export case

Provides a constructor for the specified Case.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
interface Person {
readonly name: string
}
// Creating a constructor for the specified Case
const Person = Data.case<Person>()
// Creating instances of Person
const mike1 = Person({ name: "Mike" })
const mike2 = Person({ name: "Mike" })
const john = Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

case
<
interface Person
Person
>()
// 为每个实例重复 `_tag: 'Person'`
const
const alice: Person
alice
=
const Person: Data.Case.Constructor
(args: {
readonly _tag: "Person";
readonly name: string;
}) => Person
Person
({
_tag: "Person"
_tag
: "Person",
name: string
name
: "Alice" })
const
const bob: Person
bob
=
const Person: Data.Case.Constructor
(args: {
readonly _tag: "Person";
readonly name: string;
}) => Person
Person
({
_tag: "Person"
_tag
: "Person",
name: string
name
: "Bob" })

为了简化此过程,Data.tagged 助手会自动添加标签。它遵循 Effect 生态系统中将标签字段命名为 "_tag" 的约定。

示例(使用 Data.tagged 简化标记)

Data.tagged 助手允许您只定义一次标签,使实例创建更简单。

import {
import Data
Data
} from "effect"
interface
interface Person
Person
{
readonly
Person._tag: "Person"
_tag
: "Person" // the tag
readonly
Person.name: string
name
: string
}
const
const Person: Data.Case.Constructor<Person, "_tag">
Person
=
import Data
Data
.
const tagged: <Person>(tag: "Person") => Data.Case.Constructor<Person, "_tag">

Provides a tagged constructor for the specified Case.

@example

import * as assert from "node:assert"
import { Data } from "effect"
interface Person {
readonly _tag: "Person" // the tag
readonly name: string
}
const Person = Data.tagged<Person>("Person")
const mike = Person({ name: "Mike" })
assert.deepEqual(mike, { _tag: "Person", name: "Mike" })

@since2.0.0

tagged
<
interface Person
Person
>("Person")
// `_tag` 字段会自动添加
const
const alice: Person
alice
=
const Person: Data.Case.Constructor
(args: {
readonly name: string;
}) => Person
Person
({
name: string
name
: "Alice" })
const
const bob: Person
bob
=
const Person: Data.Case.Constructor
(args: {
readonly name: string;
}) => Person
Person
({
name: string
name
: "Bob" })
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 alice: Person
alice
)
// 输出: { name: 'Alice', _tag: 'Person' }

如果您更喜欢使用类而不是普通对象,可以使用 Data.Class 作为 Data.case 的替代方案。在您想要面向类的结构,包含方法和自定义逻辑的场景中,这种方法可能感觉更自然。

示例(使用 Data.Class 实现面向类的结构)

以下是使用 Data.Class 定义 Person 类的方法:

import {
import Data
Data
,
import Equal
Equal
} from "effect"
// 定义扩展 Data.Class 的 Person 类
class
class Person
Person
extends
import Data
Data
.
const Class: new <A extends Record<string, any> = {}>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A]: A[P]; }) => Readonly<A>

Provides a constructor for a Case Class.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
class Person extends Data.Class<{ readonly name: string }> {}
// Creating instances of Person
const mike1 = new Person({ name: "Mike" })
const mike2 = new Person({ name: "Mike" })
const john = new Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

Class
<{
name: string
name
: string }> {}
// 创建 Person 实例
const
const alice: Person
alice
= new
constructor Person<{
name: string;
}>(args: {
readonly name: string;
}): Person

Provides a constructor for a Case Class.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
class Person extends Data.Class<{ readonly name: string }> {}
// Creating instances of Person
const mike1 = new Person({ name: "Mike" })
const mike2 = new Person({ name: "Mike" })
const john = new Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

Person
({
name: string
name
: "Alice" })
// 检查两个实例之间的相等性
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 Equal
Equal
.
function equals<Person, Person>(self: Person, that: Person): boolean (+1 overload)

@since2.0.0

equals
(
const alice: Person
alice
, new
constructor Person<{
name: string;
}>(args: {
readonly name: string;
}): Person

Provides a constructor for a Case Class.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
class Person extends Data.Class<{ readonly name: string }> {}
// Creating instances of Person
const mike1 = new Person({ name: "Mike" })
const mike2 = new Person({ name: "Mike" })
const john = new Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

Person
({
name: string
name
: "Alice" })))
// 输出: true

使用类的好处之一是您可以轻松添加自定义方法和 getter。这允许您扩展数据类型的功能。

示例(向类添加自定义 Getters)

在此示例中,我们向 Person 类添加 upperName getter 以返回大写的名称:

import {
import Data
Data
} from "effect"
// 使用自定义 getter 扩展 Person 类
class
class Person
Person
extends
import Data
Data
.
const Class: new <A extends Record<string, any> = {}>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A]: A[P]; }) => Readonly<A>

Provides a constructor for a Case Class.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
class Person extends Data.Class<{ readonly name: string }> {}
// Creating instances of Person
const mike1 = new Person({ name: "Mike" })
const mike2 = new Person({ name: "Mike" })
const john = new Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

Class
<{
name: string
name
: string }> {
get
Person.upperName: string
upperName
() {
return this.
name: string
name
.
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
()
}
}
// 创建实例并使用自定义 getter
const
const alice: Person
alice
= new
constructor Person<{
name: string;
}>(args: {
readonly name: string;
}): Person

Provides a constructor for a Case Class.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
class Person extends Data.Class<{ readonly name: string }> {}
// Creating instances of Person
const mike1 = new Person({ name: "Mike" })
const mike2 = new Person({ name: "Mike" })
const john = new Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)

@since2.0.0

Person
({
name: string
name
: "Alice" })
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 alice: Person
alice
.
Person.upperName: string
upperName
)
// 输出: ALICE

如果您更喜欢基于类的方法,但也希望获得不相交联合标记的好处,Data.TaggedClass 可能是一个有用的选择。它的工作方式类似于 tagged,但专为类定义而定制。

示例(定义具有内置标记的标记类)

以下是使用 Data.TaggedClass 定义 Person 类的方法。请注意,标签 "Person" 会自动添加:

import {
import Data
Data
,
import Equal
Equal
} from "effect"
// 定义带有 _tag "Person" 的标记类 Person
class
class Person
Person
extends
import Data
Data
.
const TaggedClass: <"Person">(tag: "Person") => new <A>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => Readonly<A> & {
readonly _tag: "Person";
}

Provides a Tagged constructor for a Case Class.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
class Person extends Data.TaggedClass("Person")<{ readonly name: string }> {}
// Creating instances of Person
const mike1 = new Person({ name: "Mike" })
const mike2 = new Person({ name: "Mike" })
const john = new Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)
assert.deepStrictEqual(mike1._tag, "Person")

@since2.0.0

TaggedClass
("Person")<{
name: string
name
: string }> {}
// 创建 Person 实例
const
const alice: Person
alice
= new
constructor Person<{
name: string;
}>(args: {
readonly name: string;
}): Person
Person
({
name: string
name
: "Alice" })
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 alice: Person
alice
)
// 输出: Person { name: 'Alice', _tag: 'Person' }
// 检查两个实例之间的相等性
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 Equal
Equal
.
function equals<Person, Person>(self: Person, that: Person): boolean (+1 overload)

@since2.0.0

equals
(
const alice: Person
alice
, new
constructor Person<{
name: string;
}>(args: {
readonly name: string;
}): Person
Person
({
name: string
name
: "Alice" })))
// 输出: true

使用标记类的好处之一是能够轻松添加自定义方法和 getter,根据需要扩展类的功能。

示例(向标记类添加自定义 Getters)

在此示例中,我们向 Person 类添加 upperName getter,它返回大写的名称:

import {
import Data
Data
} from "effect"
// 使用自定义 getter 扩展 Person 类
class
class Person
Person
extends
import Data
Data
.
const TaggedClass: <"Person">(tag: "Person") => new <A>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => Readonly<A> & {
readonly _tag: "Person";
}

Provides a Tagged constructor for a Case Class.

@example

import * as assert from "node:assert"
import { Data, Equal } from "effect"
class Person extends Data.TaggedClass("Person")<{ readonly name: string }> {}
// Creating instances of Person
const mike1 = new Person({ name: "Mike" })
const mike2 = new Person({ name: "Mike" })
const john = new Person({ name: "John" })
// Checking equality
assert.deepStrictEqual(Equal.equals(mike1, mike2), true)
assert.deepStrictEqual(Equal.equals(mike1, john), false)
assert.deepStrictEqual(mike1._tag, "Person")

@since2.0.0

TaggedClass
("Person")<{
name: string
name
: string }> {
get
Person.upperName: string
upperName
() {
return this.
name: string
name
.
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
()
}
}
// 创建实例并使用自定义 getter
const
const alice: Person
alice
= new
constructor Person<{
name: string;
}>(args: {
readonly name: string;
}): Person
Person
({
name: string
name
: "Alice" })
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 alice: Person
alice
.
Person.upperName: string
upperName
)
// 输出: ALICE

要创建标记结构体的不相交联合,您可以使用 Data.TaggedEnumData.taggedEnum。这些实用程序使定义和使用普通对象的联合变得简单。

传递给 Data.TaggedEnum 的类型必须是一个对象,其中键表示标签, 值定义相应数据类型的结构。

示例(定义标记联合并检查相等性)

import {
import Data
Data
,
import Equal
Equal
} from "effect"
// 使用 TaggedEnum 定义联合类型
type
type RemoteData = {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}
RemoteData
=
import Data
Data
.
type TaggedEnum<A extends Record<string, Record<string, any>> & UntaggedChildren<A>> = keyof A extends infer Tag ? Tag extends keyof A ? Simplify<{
readonly _tag: Tag;
} & { readonly [K in keyof A[Tag]]: A[Tag][K]; }> : never : never

Create a tagged enum data type, which is a union of Data structs.

import * as assert from "node:assert"
import { Data } from "effect"
type HttpError = Data.TaggedEnum<{
BadRequest: { readonly status: 400, readonly message: string }
NotFound: { readonly status: 404, readonly message: string }
}>
// Equivalent to:
type HttpErrorPlain =
| {
readonly _tag: "BadRequest"
readonly status: 400
readonly message: string
}
| {
readonly _tag: "NotFound"
readonly status: 404
readonly message: string
}

@since2.0.0

@since2.0.0

TaggedEnum
<{
type Loading: {}
Loading
: {}
type Success: {
readonly data: string;
}
Success
: { readonly
data: string
data
: string }
type Failure: {
readonly reason: string;
}
Failure
: { readonly
reason: string
reason
: string }
}>
// 为联合中的每种情况创建构造函数
const {
const Loading: Data.Case.Constructor<{
readonly _tag: "Loading";
}, "_tag">
Loading
,
const Success: Data.Case.Constructor<{
readonly _tag: "Success";
readonly data: string;
}, "_tag">
Success
,
const Failure: Data.Case.Constructor<{
readonly _tag: "Failure";
readonly reason: string;
}, "_tag">
Failure
} =
import Data
Data
.
const taggedEnum: <{
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}>() => {
readonly Loading: Data.Case.Constructor<{
readonly _tag: "Loading";
}, "_tag">;
readonly Success: Data.Case.Constructor<{
readonly _tag: "Success";
readonly data: string;
}, "_tag">;
readonly Failure: Data.Case.Constructor<{
readonly _tag: "Failure";
readonly reason: string;
}, "_tag">;
readonly $is: <Tag>(tag: Tag) => (u: unknown) => u is Extract<{
readonly _tag: "Loading";
}, {
readonly _tag: Tag;
}> | Extract<...> | Extract<...>;
readonly $match: {
...;
};
} (+4 overloads)

Create a constructor for a tagged union of Data structs.

You can also pass a TaggedEnum.WithGenerics if you want to add generics to the constructor.

@example

import { Data } from "effect"
const { BadRequest, NotFound } = Data.taggedEnum<
| { readonly _tag: "BadRequest"; readonly status: 400; readonly message: string }
| { readonly _tag: "NotFound"; readonly status: 404; readonly message: string }
>()
const notFound = NotFound({ status: 404, message: "Not Found" })

@example

import { Data } from "effect"

type MyResult<E, A> = Data.TaggedEnum<{ Failure: { readonly error: E } Success: { readonly value: A } }> interface MyResultDefinition extends Data.TaggedEnum.WithGenerics<2> { readonly taggedEnum: MyResult<this["A"], this["B"]> } const { Failure, Success } = Data.taggedEnum()

const success = Success({ value: 1 })

@since2.0.0

taggedEnum
<
type RemoteData = {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}
RemoteData
>()
// 实例化不同状态
const
const state1: {
readonly _tag: "Loading";
}
state1
=
const Loading: Data.Case.Constructor
(args: void) => {
readonly _tag: "Loading";
}
Loading
()
const
const state2: {
readonly _tag: "Success";
readonly data: string;
}
state2
=
const Success: Data.Case.Constructor
(args: {
readonly data: string;
}) => {
readonly _tag: "Success";
readonly data: string;
}
Success
({
data: string
data
: "test" })
const
const state3: {
readonly _tag: "Success";
readonly data: string;
}
state3
=
const Success: Data.Case.Constructor
(args: {
readonly data: string;
}) => {
readonly _tag: "Success";
readonly data: string;
}
Success
({
data: string
data
: "test" })
const
const state4: {
readonly _tag: "Failure";
readonly reason: string;
}
state4
=
const Failure: Data.Case.Constructor
(args: {
readonly reason: string;
}) => {
readonly _tag: "Failure";
readonly reason: string;
}
Failure
({
reason: string
reason
: "not found" })
// 检查状态之间的相等性
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 Equal
Equal
.
function equals<{
readonly _tag: "Success";
readonly data: string;
}, {
readonly _tag: "Success";
readonly data: string;
}>(self: {
readonly _tag: "Success";
readonly data: string;
}, that: {
readonly _tag: "Success";
readonly data: string;
}): boolean (+1 overload)

@since2.0.0

equals
(
const state2: {
readonly _tag: "Success";
readonly data: string;
}
state2
,
const state3: {
readonly _tag: "Success";
readonly data: string;
}
state3
)) // 输出: true
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 Equal
Equal
.
function equals<{
readonly _tag: "Success";
readonly data: string;
}, {
readonly _tag: "Failure";
readonly reason: string;
}>(self: {
readonly _tag: "Success";
readonly data: string;
}, that: {
readonly _tag: "Failure";
readonly reason: string;
}): boolean (+1 overload)

@since2.0.0

equals
(
const state2: {
readonly _tag: "Success";
readonly data: string;
}
state2
,
const state4: {
readonly _tag: "Failure";
readonly reason: string;
}
state4
)) // 输出: 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 state1: {
readonly _tag: "Loading";
}
state1
) // 输出: { _tag: 'Loading' }
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 state2: {
readonly _tag: "Success";
readonly data: string;
}
state2
) // 输出: { data: 'test', _tag: 'Success' }
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 state4: {
readonly _tag: "Failure";
readonly reason: string;
}
state4
) // 输出: { reason: 'not found', _tag: 'Failure' }

Data.taggedEnum 提供 $is$match 函数,用于方便的类型守卫和模式匹配。

示例(使用类型守卫和模式匹配)

import {
import Data
Data
} from "effect"
type
type RemoteData = {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}
RemoteData
=
import Data
Data
.
type TaggedEnum<A extends Record<string, Record<string, any>> & UntaggedChildren<A>> = keyof A extends infer Tag ? Tag extends keyof A ? Simplify<{
readonly _tag: Tag;
} & { readonly [K in keyof A[Tag]]: A[Tag][K]; }> : never : never

Create a tagged enum data type, which is a union of Data structs.

import * as assert from "node:assert"
import { Data } from "effect"
type HttpError = Data.TaggedEnum<{
BadRequest: { readonly status: 400, readonly message: string }
NotFound: { readonly status: 404, readonly message: string }
}>
// Equivalent to:
type HttpErrorPlain =
| {
readonly _tag: "BadRequest"
readonly status: 400
readonly message: string
}
| {
readonly _tag: "NotFound"
readonly status: 404
readonly message: string
}

@since2.0.0

@since2.0.0

TaggedEnum
<{
type Loading: {}
Loading
: {}
type Success: {
readonly data: string;
}
Success
: { readonly
data: string
data
: string }
type Failure: {
readonly reason: string;
}
Failure
: { readonly
reason: string
reason
: string }
}>
const {
const $is: <Tag extends "Loading" | "Success" | "Failure">(tag: Tag) => (u: unknown) => u is Extract<{
readonly _tag: "Loading";
}, {
readonly _tag: Tag;
}> | Extract<{
readonly _tag: "Success";
readonly data: string;
}, {
readonly _tag: Tag;
}> | Extract<{
readonly _tag: "Failure";
readonly reason: string;
}, {
readonly _tag: Tag;
}>
$is
,
const $match: {
<const Cases extends {
readonly Loading: (args: {
readonly _tag: "Loading";
}) => any;
readonly Success: (args: {
readonly _tag: "Success";
readonly data: string;
}) => any;
readonly Failure: (args: {
readonly _tag: "Failure";
readonly reason: string;
}) => any;
}>(cases: Cases & { [K in Exclude<keyof Cases, "Loading" | "Success" | "Failure">]: never; }): (value: {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}) => Unify<ReturnType<Cases["Loading" | "Success" | "Failure"]>>;
<const Cases extends {
...;
}>(value: {
...;
} | ... 1 more ... | {
...;
}, cases: Cases & { [K in Exclude<...>]: never; }): Unify<...>;
}
$match
,
const Loading: Data.Case.Constructor<{
readonly _tag: "Loading";
}, "_tag">
Loading
,
const Success: Data.Case.Constructor<{
readonly _tag: "Success";
readonly data: string;
}, "_tag">
Success
} =
import Data
Data
.
const taggedEnum: <{
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}>() => {
readonly Loading: Data.Case.Constructor<{
readonly _tag: "Loading";
}, "_tag">;
readonly Success: Data.Case.Constructor<{
readonly _tag: "Success";
readonly data: string;
}, "_tag">;
readonly Failure: Data.Case.Constructor<{
readonly _tag: "Failure";
readonly reason: string;
}, "_tag">;
readonly $is: <Tag>(tag: Tag) => (u: unknown) => u is Extract<{
readonly _tag: "Loading";
}, {
readonly _tag: Tag;
}> | Extract<...> | Extract<...>;
readonly $match: {
...;
};
} (+4 overloads)

Create a constructor for a tagged union of Data structs.

You can also pass a TaggedEnum.WithGenerics if you want to add generics to the constructor.

@example

import { Data } from "effect"
const { BadRequest, NotFound } = Data.taggedEnum<
| { readonly _tag: "BadRequest"; readonly status: 400; readonly message: string }
| { readonly _tag: "NotFound"; readonly status: 404; readonly message: string }
>()
const notFound = NotFound({ status: 404, message: "Not Found" })

@example

import { Data } from "effect"

type MyResult<E, A> = Data.TaggedEnum<{ Failure: { readonly error: E } Success: { readonly value: A } }> interface MyResultDefinition extends Data.TaggedEnum.WithGenerics<2> { readonly taggedEnum: MyResult<this["A"], this["B"]> } const { Failure, Success } = Data.taggedEnum()

const success = Success({ value: 1 })

@since2.0.0

taggedEnum
<
type RemoteData = {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}
RemoteData
>()
// 使用 `$is` 为 "Loading" 创建类型守卫
const
const isLoading: (u: unknown) => u is {
readonly _tag: "Loading";
}
isLoading
=
const $is: <"Loading">(tag: "Loading") => (u: unknown) => u is {
readonly _tag: "Loading";
}
$is
("Loading")
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 isLoading: (u: unknown) => u is {
readonly _tag: "Loading";
}
isLoading
(
const Loading: Data.Case.Constructor
(args: void) => {
readonly _tag: "Loading";
}
Loading
()))
// 输出: true
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 isLoading: (u: unknown) => u is {
readonly _tag: "Loading";
}
isLoading
(
const Success: Data.Case.Constructor
(args: {
readonly data: string;
}) => {
readonly _tag: "Success";
readonly data: string;
}
Success
({
data: string
data
: "test" })))
// 输出: false
// 使用 `$match` 进行模式匹配
const
const matcher: (value: {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}) => string
matcher
=
const $match: <{
readonly Loading: () => string;
readonly Success: ({ data }: {
readonly _tag: "Success";
readonly data: string;
}) => string;
readonly Failure: ({ reason }: {
readonly _tag: "Failure";
readonly reason: string;
}) => string;
}>(cases: {
readonly Loading: () => string;
readonly Success: ({ data }: {
readonly _tag: "Success";
readonly data: string;
}) => string;
readonly Failure: ({ reason }: {
readonly _tag: "Failure";
readonly reason: string;
}) => string;
} & {}) => (value: {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}) => string (+1 overload)
$match
({
type Loading: () => string
Loading
: () => "this is a Loading",
type Success: ({ data }: {
readonly _tag: "Success";
readonly data: string;
}) => string
Success
: ({
data: string
data
}) => `this is a Success: ${
data: string
data
}`,
type Failure: ({ reason }: {
readonly _tag: "Failure";
readonly reason: string;
}) => string
Failure
: ({
reason: string
reason
}) => `this is a Failure: ${
reason: string
reason
}`
})
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 matcher: (value: {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: string;
} | {
readonly _tag: "Failure";
readonly reason: string;
}) => string
matcher
(
const Success: Data.Case.Constructor
(args: {
readonly data: string;
}) => {
readonly _tag: "Success";
readonly data: string;
}
Success
({
data: string
data
: "test" })))
// 输出: "this is a Success: test"

您可以通过使用 TaggedEnum.WithGenerics 创建更灵活和可重用的标记联合。这种方法允许您定义可以动态处理不同类型的标记联合。

示例(在 TaggedEnum 中使用泛型)

import {
import Data
Data
} from "effect"
// 为 RemoteData 定义泛型 TaggedEnum
type
type RemoteData<Success, Failure> = {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: Success;
} | {
readonly _tag: "Failure";
readonly reason: Failure;
}
RemoteData
<
function (type parameter) Success in type RemoteData<Success, Failure>
Success
,
function (type parameter) Failure in type RemoteData<Success, Failure>
Failure
> =
import Data
Data
.
type TaggedEnum<A extends Record<string, Record<string, any>> & UntaggedChildren<A>> = keyof A extends infer Tag ? Tag extends keyof A ? Simplify<{
readonly _tag: Tag;
} & { readonly [K in keyof A[Tag]]: A[Tag][K]; }> : never : never

Create a tagged enum data type, which is a union of Data structs.

import * as assert from "node:assert"
import { Data } from "effect"
type HttpError = Data.TaggedEnum<{
BadRequest: { readonly status: 400, readonly message: string }
NotFound: { readonly status: 404, readonly message: string }
}>
// Equivalent to:
type HttpErrorPlain =
| {
readonly _tag: "BadRequest"
readonly status: 400
readonly message: string
}
| {
readonly _tag: "NotFound"
readonly status: 404
readonly message: string
}

@since2.0.0

@since2.0.0

TaggedEnum
<{
type Loading: {}
Loading
: {}
type Success: {
data: Success;
}
Success
: {
data: Success
data
:
function (type parameter) Success in type RemoteData<Success, Failure>
Success
}
type Failure: {
reason: Failure;
}
Failure
: {
reason: Failure
reason
:
function (type parameter) Failure in type RemoteData<Success, Failure>
Failure
}
}>
// 扩展 TaggedEnum.WithGenerics 以添加泛型
interface
interface RemoteDataDefinition
RemoteDataDefinition
extends
import Data
Data
.
namespace TaggedEnum

Create a tagged enum data type, which is a union of Data structs.

import * as assert from "node:assert"
import { Data } from "effect"
type HttpError = Data.TaggedEnum<{
BadRequest: { readonly status: 400, readonly message: string }
NotFound: { readonly status: 404, readonly message: string }
}>
// Equivalent to:
type HttpErrorPlain =
| {
readonly _tag: "BadRequest"
readonly status: 400
readonly message: string
}
| {
readonly _tag: "NotFound"
readonly status: 404
readonly message: string
}

@since2.0.0

@since2.0.0

TaggedEnum
.
interface TaggedEnum<A extends Record<string, Record<string, any>> & UntaggedChildren<A>>.WithGenerics<Count extends number>

@since2.0.0

WithGenerics
<2> {
readonly
RemoteDataDefinition.taggedEnum: {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: this["A"];
} | {
readonly _tag: "Failure";
readonly reason: this["B"];
}
taggedEnum
:
type RemoteData<Success, Failure> = {
readonly _tag: "Loading";
} | {
readonly _tag: "Success";
readonly data: Success;
} | {
readonly _tag: "Failure";
readonly reason: Failure;
}
RemoteData
<this["A"], this["B"]>
}
// 为泛型 RemoteData 创建构造函数
const {
const Loading: <A, B>(args: void) => {
readonly _tag: "Loading";
}
Loading
,
const Failure: <A, B>(args: {
readonly reason: B;
}) => {
readonly _tag: "Failure";
readonly reason: B;
}
Failure
,
const Success: <A, B>(args: {
readonly data: A;
}) => {
readonly _tag: "Success";
readonly data: A;
}
Success
} =
import Data
Data
.
const taggedEnum: <RemoteDataDefinition>() => {
readonly Loading: <A, B>(args: void) => {
readonly _tag: "Loading";
};
readonly Success: <A, B>(args: {
readonly data: A;
}) => {
readonly _tag: "Success";
readonly data: A;
};
readonly Failure: <A, B>(args: {
readonly reason: B;
}) => {
readonly _tag: "Failure";
readonly reason: B;
};
readonly $is: <Tag>(tag: Tag) => {
<T>(u: T): u is T & {
readonly _tag: Tag;
};
(u: unknown): u is Extract<{
readonly _tag: "Loading";
}, {
readonly _tag: Tag;
}> | Extract<{
readonly _tag: "Success";
readonly data: unknown;
}, {
readonly _tag: Tag;
}> | Extract<...>;
};
readonly $match: {
...;
};
} (+4 overloads)

Create a constructor for a tagged union of Data structs.

You can also pass a TaggedEnum.WithGenerics if you want to add generics to the constructor.

@example

import { Data } from "effect"
const { BadRequest, NotFound } = Data.taggedEnum<
| { readonly _tag: "BadRequest"; readonly status: 400; readonly message: string }
| { readonly _tag: "NotFound"; readonly status: 404; readonly message: string }
>()
const notFound = NotFound({ status: 404, message: "Not Found" })

@example

import { Data } from "effect"

type MyResult<E, A> = Data.TaggedEnum<{ Failure: { readonly error: E } Success: { readonly value: A } }> interface MyResultDefinition extends Data.TaggedEnum.WithGenerics<2> { readonly taggedEnum: MyResult<this["A"], this["B"]> } const { Failure, Success } = Data.taggedEnum()

const success = Success({ value: 1 })

@since2.0.0

taggedEnum
<
interface RemoteDataDefinition
RemoteDataDefinition
>()
// 使用特定类型实例化每种情况
const
const loading: {
readonly _tag: "Loading";
}
loading
=
const Loading: <unknown, unknown>(args: void) => {
readonly _tag: "Loading";
}
Loading
()
const
const failure: {
readonly _tag: "Failure";
readonly reason: string;
}
failure
=
const Failure: <unknown, string>(args: {
readonly reason: string;
}) => {
readonly _tag: "Failure";
readonly reason: string;
}
Failure
({
reason: string
reason
: "not found" })
const
const success: {
readonly _tag: "Success";
readonly data: number;
}
success
=
const Success: <number, unknown>(args: {
readonly data: number;
}) => {
readonly _tag: "Success";
readonly data: number;
}
Success
({
data: number
data
: 1 })

在 Effect 中,使用专门的构造函数简化了错误处理:

  • Error
  • TaggedError

这些构造函数使定义自定义错误类型变得简单,同时还提供有用的集成,如相等性检查和结构化错误处理。

Data.Error 允许您创建具有超出典型 message 属性的额外字段的 Error 类型。

示例(创建具有附加字段的自定义错误)

import {
import Data
Data
} from "effect"
// 定义具有附加字段的自定义错误
class
class NotFound
NotFound
extends
import Data
Data
.
const Error: new <A extends Record<string, any> = {}>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A]: A[P]; }) => YieldableError & Readonly<A>

Provides a constructor for a Case Class.

@since2.0.0

Error
<{
message: string
message
: string;
file: string
file
: string }> {}
// 创建自定义错误的实例
const
const err: NotFound
err
= new
constructor NotFound<{
message: string;
file: string;
}>(args: {
readonly message: string;
readonly file: string;
}): NotFound

Provides a constructor for a Case Class.

@since2.0.0

NotFound
({
message: string
message
: "Cannot find this file",
file: string
file
: "foo.txt"
})
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 err: NotFound
err
instanceof
var Error: ErrorConstructor
Error
)
// 输出: true
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 err: NotFound
err
.
file: string
file
)
// 输出: foo.txt
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 err: NotFound
err
)
/*
输出:
NotFound [Error]: Cannot find this file
file: 'foo.txt'
... stack trace ...
*/

您可以直接在 Effect.gen 中 yield NotFound 的实例,而无需使用 Effect.fail

示例(在 Effect.gen 中 Yield 自定义错误)

import {
import Data
Data
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
class
class NotFound
NotFound
extends
import Data
Data
.
const Error: new <A extends Record<string, any> = {}>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A]: A[P]; }) => YieldableError & Readonly<A>

Provides a constructor for a Case Class.

@since2.0.0

Error
<{
message: string
message
: string;
file: string
file
: string }> {}
const
const program: Effect.Effect<void, NotFound, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<never, NotFound, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<never, NotFound, never>>, void, never>) => Effect.Effect<void, NotFound, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
yield* new
constructor NotFound<{
message: string;
file: string;
}>(args: {
readonly message: string;
readonly file: string;
}): NotFound

Provides a constructor for a Case Class.

@since2.0.0

NotFound
({
message: string
message
: "Cannot find this file",
file: string
file
: "foo.txt"
})
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, NotFound>(effect: Effect.Effect<void, NotFound, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

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<void, NotFound, never>
program
)
/*
抛出:
Error: Cannot find this file
at ... {
name: '(FiberFailure) Error',
[Symbol(effect/Runtime/FiberFailure/Cause)]: {
_tag: 'Fail',
error: NotFound [Error]: Cannot find this file
at ...stack trace...
file: 'foo.txt'
}
}
}
*/

Effect 提供了 TaggedError API 来自动向您的自定义错误添加 _tag 字段。这简化了使用 Effect.catchTagEffect.catchTags 等 API 的错误处理。

import {
import Data
Data
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Console
Console
} from "effect"
// 定义自定义标记错误
class
class NotFound
NotFound
extends
import Data
Data
.
const TaggedError: <"NotFound">(tag: "NotFound") => new <A>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }) => YieldableError & {
readonly _tag: "NotFound";
} & Readonly<A>

@since2.0.0

TaggedError
("NotFound")<{
message: string
message
: string
file: string
file
: string
}> {}
const
const program: Effect.Effect<void, never, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<never, NotFound, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<never, NotFound, never>>, void, never>) => Effect.Effect<void, NotFound, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
yield* new
constructor NotFound<{
message: string;
file: string;
}>(args: {
readonly message: string;
readonly file: string;
}): NotFound
NotFound
({
message: string
message
: "Cannot find this file",
file: string
file
: "foo.txt"
})
}).
Pipeable.pipe<Effect.Effect<void, NotFound, never>, Effect.Effect<void, never, never>>(this: Effect.Effect<void, NotFound, never>, ab: (_: Effect.Effect<void, NotFound, never>) => Effect.Effect<void, never, never>): Effect.Effect<void, never, never> (+21 overloads)
pipe
(
// 捕获并处理标记错误
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const catchTag: <NotFound, ["NotFound"], void, never, never>(args_0: "NotFound", f: (e: NotFound) => Effect.Effect<void, never, never>) => <A, R>(self: Effect.Effect<A, NotFound, R>) => Effect.Effect<void | A, never, R> (+1 overload)

Catches and handles specific errors by their _tag field, which is used as a discriminator.

When to Use

catchTag is useful when your errors are tagged with a readonly _tag field that identifies the error type. You can use this function to handle specific error types by matching the _tag value. This allows for precise error handling, ensuring that only specific errors are caught and handled.

The error type must have a readonly _tag field to use catchTag. This field is used to identify and match errors.

Example (Handling Errors by Tag)

import { Effect, Random } from "effect"
class HttpError {
readonly _tag = "HttpError"
}
class ValidationError {
readonly _tag = "ValidationError"
}
// ┌─── Effect<string, HttpError | ValidationError, never>
// ▼
const program = Effect.gen(function* () {
const n1 = yield* Random.next
const n2 = yield* Random.next
if (n1 < 0.5) {
yield* Effect.fail(new HttpError())
}
if (n2 < 0.5) {
yield* Effect.fail(new ValidationError())
}
return "some result"
})
// ┌─── Effect<string, ValidationError, never>
// ▼
const recovered = program.pipe(
// Only handle HttpError errors
Effect.catchTag("HttpError", (_HttpError) =>
Effect.succeed("Recovering from HttpError")
)
)

@seecatchTags for a version that allows you to handle multiple error types at once.

@since2.0.0

catchTag
("NotFound", (
err: NotFound
err
) =>
import Console
Console
.
const error: (...args: ReadonlyArray<any>) => Effect.Effect<void>

@since2.0.0

error
(`${
err: NotFound
err
.
Error.message: string
message
} (${
err: NotFound
err
.
file: string
file
})`)
)
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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<void, never, never>
program
)
// 输出: Cannot find this file (foo.txt)

使用 Data.ErrorData.TaggedError 创建的错误可以包含 cause 属性,与 JavaScript Error 的原生 cause 功能集成,以进行更详细的错误跟踪。

示例(使用 cause 属性)

import {
import Data
Data
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// 定义具有 cause 属性的错误
class
class MyError
MyError
extends
import Data
Data
.
const Error: new <A extends Record<string, any> = {}>(args: Equals<A, {}> extends true ? void : { readonly [P in keyof A]: A[P]; }) => YieldableError & Readonly<A>

Provides a constructor for a Case Class.

@since2.0.0

Error
<{
cause: Error
cause
:
interface Error
Error
}> {}
const
const program: Effect.Effect<void, MyError, never>
program
=
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<never, MyError, never>>, void>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<never, MyError, never>>, void, never>) => Effect.Effect<void, MyError, never> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to Use

Effect.gen allows you to write code that looks and behaves like synchronous code, but it can handle asynchronous tasks, errors, and complex control flow (like loops and conditions). It helps make asynchronous code more readable and easier to manage.

The generator functions work similarly to async/await but with more explicit control over the execution of effects. You can yield* values from effects and return the final result at the end.

Example

import { Effect } from "effect"
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, Error> =>
discountRate === 0
? Effect.fail(new Error("Discount rate cannot be zero"))
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function* () {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})

@since2.0.0

gen
(function* () {
yield* new
constructor MyError<{
cause: Error;
}>(args: {
readonly cause: Error;
}): MyError

Provides a constructor for a Case Class.

@since2.0.0

MyError
({
cause: Error
cause
: new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("Something went wrong")
})
})
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromise: <void, MyError>(effect: Effect.Effect<void, MyError, never>, options?: {
readonly signal?: AbortSignal | undefined;
} | undefined) => Promise<void>

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<void, MyError, never>
program
)
/*
抛出:
Error: An error has occurred
at ... {
name: '(FiberFailure) Error',
[Symbol(effect/Runtime/FiberFailure/Cause)]: {
_tag: 'Fail',
error: MyError
at ...
[cause]: Error: Something went wrong
at ...
*/