Skip to content

Schema 转换

在使用模式时,转换非常重要。它们允许您将数据从一种类型更改为另一种类型。例如,您可能将字符串解析为数字或将日期字符串转换为 Date 对象。

Schema.transformSchema.transformOrFail 函数帮助您连接两个模式,以便您可以在它们之间转换数据。

Schema.transform 通过获取一个模式(“源”)的输出并将其作为另一个模式(“目标”)的输入来创建新模式。当您知道转换总是会成功时使用此方法。如果可能失败,请改用 Schema.transformOrFail

“输出”和”输入”取决于您正在执行的操作(解码或编码):

解码时:

  • 源模式 Schema<SourceType, SourceEncoded> 产生 SourceType
  • 目标模式 Schema<TargetType, TargetEncoded> 期望 TargetEncoded
  • 解码路径如下所示:SourceEncodedTargetType

如果 SourceTypeTargetEncoded 不同,您可以提供 decode 函数将源模式的输出转换为目标模式的输入。

编码时:

  • 目标模式 Schema<TargetType, TargetEncoded> 产生 TargetEncoded
  • 源模式 Schema<SourceType, SourceEncoded> 期望 SourceType
  • 编码路径如下所示:TargetTypeSourceEncoded

如果 TargetEncodedSourceType 不同,您可以提供 encode 函数将目标模式的输出转换为源模式的输入。

在此示例中,我们从接受 "on""off" 的模式开始,并将其转换为布尔模式。decode 函数将 "on" 转换为 true,将 "off" 转换为 falseencode 函数执行相反的操作。这为我们提供了 Schema<boolean, "on" | "off">

示例(将字符串转换为布尔值)

import {
import Schema
Schema
} from "effect"
// 将 "on"/"off" 转换为布尔值并返回
const
const BooleanFromString: Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>
BooleanFromString
=
import Schema
Schema
.
const transform: <typeof Schema.Boolean, Schema.Literal<["on", "off"]>>(from: Schema.Literal<["on", "off"]>, to: typeof Schema.Boolean, options: {
readonly decode: (fromA: "on" | "off", fromI: "on" | "off") => boolean;
readonly encode: (toI: boolean, toA: boolean) => "on" | "off";
readonly strict?: true;
} | {
readonly decode: (fromA: "on" | "off", fromI: "on" | "off") => unknown;
readonly encode: (toI: boolean, toA: boolean) => unknown;
readonly strict: false;
}) => Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided mapping functions.

@since3.10.0

transform
(
// 源模式:"on" 或 "off"
import Schema
Schema
.
function Literal<["on", "off"]>(literals_0: "on", literals_1: "off"): Schema.Literal<["on", "off"]> (+2 overloads)

@since3.10.0

Literal
("on", "off"),
// 目标模式:布尔值
import Schema
Schema
.
class Boolean
export Boolean

@since3.10.0

Boolean
,
{
// 可选,但您可以从 TypeScript 获得更好的错误消息
strict?: true
strict
: true,
// 转换以将源模式的输出("on" | "off")
// 转换为目标模式的输入(布尔值)
decode: (fromA: "on" | "off", fromI: "on" | "off") => boolean
decode
: (
literal: "on" | "off"
literal
) =>
literal: "on" | "off"
literal
=== "on", // 这里总是成功
// 反向转换
encode: (toI: boolean, toA: boolean) => "on" | "off"
encode
: (
bool: boolean
bool
) => (
bool: boolean
bool
? "on" : "off")
}
)
// ┌─── "on" | "off"
// ▼
type
type Encoded = "on" | "off"
Encoded
= typeof
const BooleanFromString: Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>
BooleanFromString
.
Schema<boolean, "on" | "off", never>.Encoded: "on" | "off"
Encoded
// ┌─── boolean
// ▼
type
type Type = boolean
Type
= typeof
const BooleanFromString: Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>
BooleanFromString
.
Schema<boolean, "on" | "off", never>.Type: boolean
Type
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 Schema
Schema
.
decodeUnknownSync<boolean, "on" | "off">(schema: Schema.Schema<boolean, "on" | "off", never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => boolean
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const BooleanFromString: Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>
BooleanFromString
)("on"))
// 输出:true

上面的decode函数本身永远不会失败。但是,如果输入不符合源模式,完整的解码过程仍然可能失败。例如,如果您提供"wrong"而不是"on""off",源模式将在调用decode之前失败。

示例(处理无效输入)

import {
import Schema
Schema
} from "effect"
// Convert "on"/"off" to boolean and back
9 collapsed lines
const
const BooleanFromString: Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>
BooleanFromString
=
import Schema
Schema
.
const transform: <typeof Schema.Boolean, Schema.Literal<["on", "off"]>>(from: Schema.Literal<["on", "off"]>, to: typeof Schema.Boolean, options: {
readonly decode: (fromA: "on" | "off", fromI: "on" | "off") => boolean;
readonly encode: (toI: boolean, toA: boolean) => "on" | "off";
readonly strict?: true;
} | {
readonly decode: (fromA: "on" | "off", fromI: "on" | "off") => unknown;
readonly encode: (toI: boolean, toA: boolean) => unknown;
readonly strict: false;
}) => Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided mapping functions.

@since3.10.0

transform
(
import Schema
Schema
.
function Literal<["on", "off"]>(literals_0: "on", literals_1: "off"): Schema.Literal<["on", "off"]> (+2 overloads)

@since3.10.0

Literal
("on", "off"),
import Schema
Schema
.
class Boolean
export Boolean

@since3.10.0

Boolean
,
{
strict?: true
strict
: true,
decode: (fromA: "on" | "off", fromI: "on" | "off") => boolean
decode
: (
s: "on" | "off"
s
) =>
s: "on" | "off"
s
=== "on",
encode: (toI: boolean, toA: boolean) => "on" | "off"
encode
: (
bool: boolean
bool
) => (
bool: boolean
bool
? "on" : "off")
}
)
// 提供源模式不允许的输入
import Schema
Schema
.
decodeUnknownSync<boolean, "on" | "off">(schema: Schema.Schema<boolean, "on" | "off", never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => boolean
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const BooleanFromString: Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>
BooleanFromString
)("wrong")
/*
抛出:
ParseError: ("on" | "off" <-> boolean)
└─ Encoded side transformation failure
└─ "on" | "off"
├─ Expected "on", actual "wrong"
└─ Expected "off", actual "wrong"
*/

以下是源模式和目标模式都转换其数据的示例:

  • 源模式是Schema.NumberFromString,即Schema<number, string>
  • 目标模式是BooleanFromString(上面定义的),即Schema<boolean, "on" | "off">

此示例涉及四种类型并需要两次转换:

  • 解码时,将number转换为"on" | "off"。例如,将任何正数视为"on"
  • 编码时,将"on" | "off"转换回number。例如,将"on"视为1,将"off"视为-1

通过组合这些转换,我们得到一个将字符串解码为布尔值并将布尔值编码回字符串的模式。结果模式是Schema<boolean, string>

示例(组合两个转换模式)

import {
import Schema
Schema
} from "effect"
// Convert "on"/"off" to boolean and back
9 collapsed lines
const
const BooleanFromString: Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>
BooleanFromString
=
import Schema
Schema
.
const transform: <typeof Schema.Boolean, Schema.Literal<["on", "off"]>>(from: Schema.Literal<["on", "off"]>, to: typeof Schema.Boolean, options: {
readonly decode: (fromA: "on" | "off", fromI: "on" | "off") => boolean;
readonly encode: (toI: boolean, toA: boolean) => "on" | "off";
readonly strict?: true;
} | {
readonly decode: (fromA: "on" | "off", fromI: "on" | "off") => unknown;
readonly encode: (toI: boolean, toA: boolean) => unknown;
readonly strict: false;
}) => Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided mapping functions.

@since3.10.0

transform
(
import Schema
Schema
.
function Literal<["on", "off"]>(literals_0: "on", literals_1: "off"): Schema.Literal<["on", "off"]> (+2 overloads)

@since3.10.0

Literal
("on", "off"),
import Schema
Schema
.
class Boolean
export Boolean

@since3.10.0

Boolean
,
{
strict?: true
strict
: true,
decode: (fromA: "on" | "off", fromI: "on" | "off") => boolean
decode
: (
s: "on" | "off"
s
) =>
s: "on" | "off"
s
=== "on",
encode: (toI: boolean, toA: boolean) => "on" | "off"
encode
: (
bool: boolean
bool
) => (
bool: boolean
bool
? "on" : "off")
}
)
const
const BooleanFromNumericString: Schema.transform<typeof Schema.NumberFromString, Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>>
BooleanFromNumericString
=
import Schema
Schema
.
const transform: <Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>, typeof Schema.NumberFromString>(from: typeof Schema.NumberFromString, to: Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>, options: {
readonly decode: (fromA: number, fromI: string) => "on" | "off";
readonly encode: (toI: "on" | "off", toA: boolean) => number;
readonly strict?: true;
} | {
readonly decode: (fromA: number, fromI: string) => unknown;
readonly encode: (toI: "on" | "off", toA: boolean) => unknown;
readonly strict: false;
}) => Schema.transform<...> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided mapping functions.

@since3.10.0

transform
(
// Source schema: Convert string -> number
import Schema
Schema
.
class NumberFromString

This schema transforms a string into a number by parsing the string using the parse function of the effect/Number module.

It returns an error if the value can't be converted (for example when non-numeric characters are provided).

The following special string values are supported: "NaN", "Infinity", "-Infinity".

@since3.10.0

NumberFromString
,
// Target schema: Convert "on"/"off" -> boolean
const BooleanFromString: Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>
BooleanFromString
,
{
strict?: true
strict
: true,
// 如果数字为正,使用"on",否则使用"off"
decode: (fromA: number, fromI: string) => "on" | "off"
decode
: (
n: number
n
) => (
n: number
n
> 0 ? "on" : "off"),
// 如果布尔值为"on",使用1,否则使用-1
encode: (toI: "on" | "off", toA: boolean) => number
encode
: (
bool: "on" | "off"
bool
) => (
bool: "on" | "off"
bool
=== "on" ? 1 : -1)
}
)
// ┌─── string
// ▼
type
type Encoded = string
Encoded
= typeof
const BooleanFromNumericString: Schema.transform<typeof Schema.NumberFromString, Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>>
BooleanFromNumericString
.
Schema<boolean, string, never>.Encoded: string
Encoded
// ┌─── boolean
// ▼
type
type Type = boolean
Type
= typeof
const BooleanFromNumericString: Schema.transform<typeof Schema.NumberFromString, Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>>
BooleanFromNumericString
.
Schema<boolean, string, never>.Type: boolean
Type
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 Schema
Schema
.
decodeUnknownSync<boolean, string>(schema: Schema.Schema<boolean, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => boolean
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const BooleanFromNumericString: Schema.transform<typeof Schema.NumberFromString, Schema.transform<Schema.Literal<["on", "off"]>, typeof Schema.Boolean>>
BooleanFromNumericString
)("100"))
// 输出:true

示例(将数组转换为ReadonlySet)

在此示例中,我们将数组转换为ReadonlySetdecode函数接受一个数组并创建一个新的ReadonlySetencode函数将集合转换回数组。我们还提供数组项的模式,以便它们得到正确验证。

import {
import Schema
Schema
} from "effect"
// 此函数构建一个在只读数组和只读项集合之间转换的模式
const
const ReadonlySetFromArray: <A, I, R>(itemSchema: Schema.Schema<A, I, R>) => Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
ReadonlySetFromArray
= <
function (type parameter) A in <A, I, R>(itemSchema: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
A
,
function (type parameter) I in <A, I, R>(itemSchema: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
I
,
function (type parameter) R in <A, I, R>(itemSchema: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
R
>(
itemSchema: Schema.Schema<A, I, R>
itemSchema
:
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never>

@since3.10.0

@since3.10.0

Schema
<
function (type parameter) A in <A, I, R>(itemSchema: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
A
,
function (type parameter) I in <A, I, R>(itemSchema: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
I
,
function (type parameter) R in <A, I, R>(itemSchema: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
R
>
):
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never>

@since3.10.0

@since3.10.0

Schema
<
interface ReadonlySet<T>
ReadonlySet
<
function (type parameter) A in <A, I, R>(itemSchema: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
A
>,
interface ReadonlyArray<T>
ReadonlyArray
<
function (type parameter) I in <A, I, R>(itemSchema: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
I
>,
function (type parameter) R in <A, I, R>(itemSchema: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlyArray<I>, R>
R
> =>
import Schema
Schema
.
const transform: <Schema.ReadonlySetFromSelf<Schema.SchemaClass<A, A, never>>, Schema.Array$<Schema.Schema<A, I, R>>>(from: Schema.Array$<Schema.Schema<A, I, R>>, to: Schema.ReadonlySetFromSelf<Schema.SchemaClass<A, A, never>>, options: {
readonly decode: (fromA: readonly A[], fromI: readonly I[]) => ReadonlySet<A>;
readonly encode: (toI: ReadonlySet<A>, toA: ReadonlySet<A>) => readonly A[];
readonly strict?: true;
} | {
readonly decode: (fromA: readonly A[], fromI: readonly I[]) => unknown;
readonly encode: (toI: ReadonlySet<...>, toA: ReadonlySet<...>) => unknown;
readonly strict: false;
}) => Schema.transform<...> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided mapping functions.

@since3.10.0

transform
(
// 源模式:项目数组
import Schema
Schema
.
Array<Schema.Schema<A, I, R>>(value: Schema.Schema<A, I, R>): Schema.Array$<Schema.Schema<A, I, R>>
export Array

@since3.10.0

Array
(
itemSchema: Schema.Schema<A, I, R>
itemSchema
),
// 目标模式:只读项集合
// **重要** 我们在这里使用`Schema.typeSchema`来获取项的模式
// 以避免对元素进行两次解码
import Schema
Schema
.
const ReadonlySetFromSelf: <Schema.SchemaClass<A, A, never>>(value: Schema.SchemaClass<A, A, never>) => Schema.ReadonlySetFromSelf<Schema.SchemaClass<A, A, never>>

@since3.10.0

ReadonlySetFromSelf
(
import Schema
Schema
.
const typeSchema: <A, I, R>(schema: Schema.Schema<A, I, R>) => Schema.SchemaClass<A, A, never>

The typeSchema function allows you to extract the Type portion of a schema, creating a new schema that conforms to the properties defined in the original schema without considering the initial encoding or transformation processes.

@since3.10.0

typeSchema
(
itemSchema: Schema.Schema<A, I, R>
itemSchema
)),
{
strict?: true
strict
: true,
decode: (fromA: readonly A[], fromI: readonly I[]) => ReadonlySet<A>
decode
: (
items: readonly A[]
items
) => new
var Set: SetConstructor
new <A>(iterable?: Iterable<A> | null | undefined) => Set<A> (+1 overload)
Set
(
items: readonly A[]
items
),
encode: (toI: ReadonlySet<A>, toA: ReadonlySet<A>) => readonly A[]
encode
: (
set: ReadonlySet<A>
set
) =>
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<A>(iterable: Iterable<A> | ArrayLike<A>): A[] (+3 overloads)

Creates an array from an iterable object.

@paramiterable An iterable object to convert to an array.

from
(
set: ReadonlySet<A>
set
.
ReadonlySet<A>.values(): SetIterator<A>

Returns an iterable of values in the set.

values
())
}
)
const
const schema: Schema.Schema<ReadonlySet<string>, readonly string[], never>
schema
=
const ReadonlySetFromArray: <string, string, never>(itemSchema: Schema.Schema<string, string, never>) => Schema.Schema<ReadonlySet<string>, readonly string[], never>
ReadonlySetFromArray
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
)
// ┌─── readonly string[]
// ▼
type
type Encoded = readonly string[]
Encoded
= typeof
const schema: Schema.Schema<ReadonlySet<string>, readonly string[], never>
schema
.
Schema<ReadonlySet<string>, readonly string[], never>.Encoded: readonly string[]
Encoded
// ┌─── ReadonlySet<string>
// ▼
type
type Type = ReadonlySet<string>
Type
= typeof
const schema: Schema.Schema<ReadonlySet<string>, readonly string[], never>
schema
.
Schema<ReadonlySet<string>, readonly string[], never>.Type: ReadonlySet<string>
Type
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 Schema
Schema
.
decodeUnknownSync<ReadonlySet<string>, readonly string[]>(schema: Schema.Schema<ReadonlySet<string>, readonly string[], never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => ReadonlySet<string>
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Schema<ReadonlySet<string>, readonly string[], never>
schema
)(["a", "b", "c"]))
// 输出:Set(3) { 'a', 'b', 'c' }
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 Schema
Schema
.
encodeSync<ReadonlySet<string>, readonly string[]>(schema: Schema.Schema<ReadonlySet<string>, readonly string[], never>, options?: ParseOptions): (a: ReadonlySet<string>, overrideOptions?: ParseOptions) => readonly string[]
export encodeSync

@since3.10.0

encodeSync
(
const schema: Schema.Schema<ReadonlySet<string>, readonly string[], never>
schema
)(new
var Set: SetConstructor
new <string>(iterable?: Iterable<string> | null | undefined) => Set<string> (+1 overload)
Set
(["a", "b", "c"])))
// 输出:[ 'a', 'b', 'c' ]

在某些情况下,严格的类型检查可能在数据转换过程中造成问题,特别是当类型在特定转换中可能略有不同时。为了解决这些场景,Schema.transform提供了strict: false选项,它放宽类型约束并允许更灵活的转换。

示例(创建限制构造函数)

让我们考虑这样一个场景:您需要定义一个构造函数clamp,确保数字在特定范围内。此函数返回一个将数字”限制”到指定最小和最大范围的模式:

import {
import Schema
Schema
,
import Number
Number
} from "effect"
const
const clamp: (minimum: number, maximum: number) => <A extends number, I, R>(self: Schema.Schema<A, I, R>) => Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
clamp
=
(
minimum: number
minimum
: number,
maximum: number
maximum
: number) =>
<
function (type parameter) A in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
A
extends number,
function (type parameter) I in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
I
,
function (type parameter) R in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
R
>(
self: Schema.Schema<A, I, R>
self
:
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never>

@since3.10.0

@since3.10.0

Schema
<
function (type parameter) A in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
A
,
function (type parameter) I in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
I
,
function (type parameter) R in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
R
>) =>
import Schema
Schema
.
const transform: <Schema.filter<Schema.SchemaClass<A, A, never>>, Schema.Schema<A, I, R>>(from: Schema.Schema<A, I, R>, to: Schema.filter<Schema.SchemaClass<A, A, never>>, options: {
readonly decode: (fromA: A, fromI: I) => A;
readonly encode: (toI: A, toA: A) => A;
readonly strict?: true;
} | {
readonly decode: (fromA: A, fromI: I) => unknown;
readonly encode: (toI: A, toA: A) => unknown;
readonly strict: false;
}) => Schema.transform<Schema.Schema<A, I, R>, Schema.filter<...>> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided mapping functions.

@since3.10.0

transform
(
// 源模式
self: Schema.Schema<A, I, R>
self
,
// 目标模式:基于最小/最大范围过滤
self: Schema.Schema<A, I, R>
self
.
Pipeable.pipe<Schema.Schema<A, I, R>, Schema.SchemaClass<A, A, never>, Schema.filter<Schema.SchemaClass<A, A, never>>>(this: Schema.Schema<A, I, R>, ab: (_: Schema.Schema<A, I, R>) => Schema.SchemaClass<A, A, never>, bc: (_: Schema.SchemaClass<A, A, never>) => Schema.filter<Schema.SchemaClass<A, A, never>>): Schema.filter<Schema.SchemaClass<A, A, never>> (+21 overloads)
pipe
(
import Schema
Schema
.
const typeSchema: <A, I, R>(schema: Schema.Schema<A, I, R>) => Schema.SchemaClass<A>

The typeSchema function allows you to extract the Type portion of a schema, creating a new schema that conforms to the properties defined in the original schema without considering the initial encoding or transformation processes.

@since3.10.0

typeSchema
,
import Schema
Schema
.
function filter<Schema.SchemaClass<A, A, never>>(predicate: (a: NoInfer<A>, options: ParseOptions, self: Refinement) => FilterReturnType, annotations?: Schema.Annotations.Filter<NoInfer<A>, NoInfer<A>> | undefined): (self: Schema.SchemaClass<A, A, never>) => Schema.filter<Schema.SchemaClass<A, A, never>> (+2 overloads)

@since3.10.0

filter
((
a: A extends number
a
) =>
a: A extends number
a
<=
minimum: number
minimum
||
a: A extends number
a
>=
maximum: number
maximum
)
),
{
Error ts(2345) ― Argument of type '{ strict: true; decode: (a: A) => number; encode: (a: A) => A; }' is not assignable to parameter of type '{ readonly decode: (fromA: A, fromI: I) => A; readonly encode: (toI: A, toA: A) => A; readonly strict?: true; } | { readonly decode: (fromA: A, fromI: I) => unknown; readonly encode: (toI: A, toA: A) => unknown; readonly strict: false; }'. The types returned by 'decode(...)' are incompatible between these types. Type 'number' is not assignable to type 'A'. 'number' is assignable to the constraint of type 'A', but 'A' could be instantiated with a different subtype of constraint 'number'.
strict?: true
strict
: true,
// 将数字限制在指定范围内
decode: (fromA: A, fromI: I) => A
decode
: (
a: A extends number
a
) =>
import Number
Number
.
const clamp: (self: number, options: {
minimum: number;
maximum: number;
}) => number (+1 overload)

Restricts the given number to be within the range specified by the minimum and maximum values.

  • If the number is less than the minimum value, the function returns the minimum value.
  • If the number is greater than the maximum value, the function returns the maximum value.
  • Otherwise, it returns the original number.

@memberofNumber

@since2.0.0

@example

import * as assert from "node:assert/strict"
import { Number } from "effect"
const clamp = Number.clamp({ minimum: 1, maximum: 5 })
assert.equal(clamp(3), 3)
assert.equal(clamp(0), 1)
assert.equal(clamp(6), 5)

clamp
(
a: A extends number
a
, {
minimum: number
minimum
,
maximum: number
maximum
}),
encode: (toI: A, toA: A) => A
encode
: (
a: A extends number
a
) =>
a: A extends number
a
}
)

在此示例中,Number.clamp返回一个可能不被识别为特定A类型的number,这在严格检查下导致类型不匹配。

有两种方法可以解决这个问题:

  1. 使用类型断言: 添加类型转换可以强制将返回类型视为类型A

    decode: (a) => Number.clamp(a, { minimum, maximum }) as A
  2. 使用非严格选项: 在转换选项中设置strict: false允许模式绕过TypeScript的一些类型检查规则,适应类型差异:

    import {
    import Schema
    Schema
    ,
    import Number
    Number
    } from "effect"
    const
    const clamp: (minimum: number, maximum: number) => <A extends number, I, R>(self: Schema.Schema<A, I, R>) => Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
    clamp
    =
    (
    minimum: number
    minimum
    : number,
    maximum: number
    maximum
    : number) =>
    <
    function (type parameter) A in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
    A
    extends number,
    function (type parameter) I in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
    I
    ,
    function (type parameter) R in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
    R
    >(
    self: Schema.Schema<A, I, R>
    self
    :
    import Schema
    Schema
    .
    interface Schema<in out A, in out I = A, out R = never>

    @since3.10.0

    @since3.10.0

    Schema
    <
    function (type parameter) A in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
    A
    ,
    function (type parameter) I in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
    I
    ,
    function (type parameter) R in <A extends number, I, R>(self: Schema.Schema<A, I, R>): Schema.transform<Schema.Schema<A, I, R>, Schema.filter<Schema.SchemaClass<A, A, never>>>
    R
    >) =>
    import Schema
    Schema
    .
    const transform: <Schema.filter<Schema.SchemaClass<A, A, never>>, Schema.Schema<A, I, R>>(from: Schema.Schema<A, I, R>, to: Schema.filter<Schema.SchemaClass<A, A, never>>, options: {
    readonly decode: (fromA: A, fromI: I) => A;
    readonly encode: (toI: A, toA: A) => A;
    readonly strict?: true;
    } | {
    readonly decode: (fromA: A, fromI: I) => unknown;
    readonly encode: (toI: A, toA: A) => unknown;
    readonly strict: false;
    }) => Schema.transform<Schema.Schema<A, I, R>, Schema.filter<...>> (+1 overload)

    Create a new Schema by transforming the input and output of an existing Schema using the provided mapping functions.

    @since3.10.0

    transform
    (
    self: Schema.Schema<A, I, R>
    self
    ,
    self: Schema.Schema<A, I, R>
    self
    .
    Pipeable.pipe<Schema.Schema<A, I, R>, Schema.SchemaClass<A, A, never>, Schema.filter<Schema.SchemaClass<A, A, never>>>(this: Schema.Schema<A, I, R>, ab: (_: Schema.Schema<A, I, R>) => Schema.SchemaClass<A, A, never>, bc: (_: Schema.SchemaClass<A, A, never>) => Schema.filter<Schema.SchemaClass<A, A, never>>): Schema.filter<Schema.SchemaClass<A, A, never>> (+21 overloads)
    pipe
    (
    import Schema
    Schema
    .
    const typeSchema: <A, I, R>(schema: Schema.Schema<A, I, R>) => Schema.SchemaClass<A>

    The typeSchema function allows you to extract the Type portion of a schema, creating a new schema that conforms to the properties defined in the original schema without considering the initial encoding or transformation processes.

    @since3.10.0

    typeSchema
    ,
    import Schema
    Schema
    .
    function filter<Schema.SchemaClass<A, A, never>>(predicate: (a: NoInfer<A>, options: ParseOptions, self: Refinement) => FilterReturnType, annotations?: Schema.Annotations.Filter<NoInfer<A>, NoInfer<A>> | undefined): (self: Schema.SchemaClass<A, A, never>) => Schema.filter<Schema.SchemaClass<A, A, never>> (+2 overloads)

    @since3.10.0

    filter
    ((
    a: A extends number
    a
    ) =>
    a: A extends number
    a
    >=
    minimum: number
    minimum
    &&
    a: A extends number
    a
    <=
    maximum: number
    maximum
    )
    ),
    {
    strict: false
    strict
    : false,
    decode: (fromA: A, fromI: I) => unknown
    decode
    : (
    a: A extends number
    a
    ) =>
    import Number
    Number
    .
    const clamp: (self: number, options: {
    minimum: number;
    maximum: number;
    }) => number (+1 overload)

    Restricts the given number to be within the range specified by the minimum and maximum values.

    • If the number is less than the minimum value, the function returns the minimum value.
    • If the number is greater than the maximum value, the function returns the maximum value.
    • Otherwise, it returns the original number.

    @memberofNumber

    @since2.0.0

    @example

    import * as assert from "node:assert/strict"
    import { Number } from "effect"
    const clamp = Number.clamp({ minimum: 1, maximum: 5 })
    assert.equal(clamp(3), 3)
    assert.equal(clamp(0), 1)
    assert.equal(clamp(6), 5)

    clamp
    (
    a: A extends number
    a
    , {
    minimum: number
    minimum
    ,
    maximum: number
    maximum
    }),
    encode: (toI: A, toA: A) => unknown
    encode
    : (
    a: A extends number
    a
    ) =>
    a: A extends number
    a
    }
    )

虽然Schema.transform函数适用于无错误转换, Schema.transformOrFail函数专为更复杂的场景而设计,其中转换可能在解码或编码阶段失败

此函数使解码/编码函数能够返回成功结果或错误, 使其特别适用于验证和处理可能不总是符合预期格式的数据。

Schema.transformOrFail函数利用ParseResult模块来管理潜在错误:

构造函数描述
ParseResult.succeed表示成功的转换,没有发生错误。
ParseResult.fail表示失败的转换,基于提供的ParseIssue创建新的ParseError

此外,ParseResult模块提供了处理各种类型解析问题的构造函数,例如:

解析问题类型描述
Type表示类型不匹配错误。
Missing当缺少必需字段时使用。
Unexpected用于模式中不允许的意外字段。
Forbidden标记模式禁止的解码或编码操作。
Pointer指向数据中发生问题的特定位置。
Refinement当值不满足特定细化或约束时使用。
Transformation标记从一种类型转换为另一种类型时发生的问题。
Composite表示复合错误,将多个问题合并为一个,对分组错误很有帮助。

这些工具允许详细和特定的错误处理,增强数据处理操作的可靠性。

示例(将字符串转换为数字)

Schema.transformOrFail的常见用例是将数字的字符串表示转换为实际的数字类型。这种场景在处理用户输入或来自外部源的数据时很典型。

import {
import ParseResult
ParseResult
,
import Schema
Schema
} from "effect"
export const
const NumberFromString: Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never>
NumberFromString
=
import Schema
Schema
.
const transformOrFail: <typeof Schema.Number, typeof Schema.String, never, never>(from: typeof Schema.String, to: typeof Schema.Number, options: {
readonly decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect<number, ParseResult.ParseIssue, never>;
readonly encode: (toI: number, options: ParseOptions, ast: Transformation, toA: number) => Effect<string, ParseResult.ParseIssue, never>;
readonly strict?: true;
} | {
...;
}) => Schema.transformOrFail<...> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided decoding functions.

@since3.10.0

transformOrFail
(
// 源模式:接受任何字符串
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
// 目标模式:期望数字
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
{
// 可选,但您可以从TypeScript获得更好的错误消息
strict?: true
strict
: true,
decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect<number, ParseResult.ParseIssue, never>
decode
: (
input: string
input
,
options: ParseOptions
options
,
ast: Transformation
ast
) => {
const
const parsed: number
parsed
=
function parseFloat(string: string): number

Converts a string to a floating-point number.

@paramstring A string that contains a floating-point number.

parseFloat
(
input: string
input
)
// 如果解析失败(NaN),返回带有自定义错误的ParseError
if (
function isNaN(number: number): boolean

Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).

@paramnumber A numeric value.

isNaN
(
const parsed: number
parsed
)) {
return
import ParseResult
ParseResult
.
const fail: (issue: ParseResult.ParseIssue) => Either<never, ParseResult.ParseIssue>

@since3.10.0

fail
(
// 创建类型不匹配错误
new
import ParseResult
ParseResult
.
constructor Type(ast: AST, actual: unknown, message?: string | undefined): ParseResult.Type

The Type variant of the ParseIssue type represents an error that occurs when the actual value is not of the expected type. The ast field specifies the expected type, and the actual field contains the value that caused the error.

@since3.10.0

Type
(
// 提供模式的抽象语法树作为上下文
ast: Transformation
ast
,
// 包含有问题的输入
input: string
input
,
// 可选的自定义错误消息
"Failed to convert string to number"
)
)
}
return
import ParseResult
ParseResult
.
const succeed: <number>(a: number) => Either<number, ParseResult.ParseIssue>

@since3.10.0

succeed
(
const parsed: number
parsed
)
},
encode: (toI: number, options: ParseOptions, ast: Transformation, toA: number) => Effect<string, ParseResult.ParseIssue, never>
encode
: (
input: number
input
,
options: ParseOptions
options
,
ast: Transformation
ast
) =>
import ParseResult
ParseResult
.
const succeed: <string>(a: string) => Either<string, ParseResult.ParseIssue>

@since3.10.0

succeed
(
input: number
input
.
Number.toString(radix?: number): string

Returns a string representation of an object.

@paramradix Specifies a radix for converting numeric values to strings. This value is only used for numbers.

toString
())
}
)
// ┌─── string
// ▼
type
type Encoded = string
Encoded
= typeof
const NumberFromString: Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never>
NumberFromString
.
Schema<number, string, never>.Encoded: string
Encoded
// ┌─── number
// ▼
type
type Type = number
Type
= typeof
const NumberFromString: Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never>
NumberFromString
.
Schema<number, string, never>.Type: number
Type
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 Schema
Schema
.
decodeUnknownSync<number, string>(schema: Schema.Schema<number, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => number
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const NumberFromString: Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never>
NumberFromString
)("123"))
// 输出:123
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 Schema
Schema
.
decodeUnknownSync<number, string>(schema: Schema.Schema<number, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => number
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const NumberFromString: Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never>
NumberFromString
)("-"))
/*
抛出:
ParseError: (string <-> number)
└─ Transformation process failure
└─ Failed to convert string to number
*/

无论是decode还是encode函数,不仅接收要转换的值(input),还接收用户在使用结果模式时设置的解析选项,以及ast,它表示您正在转换的模式的低级定义。

在现代应用程序中,特别是那些与外部API交互的应用程序,您可能需要异步转换数据。Schema.transformOrFail通过允许您返回Effect来支持异步转换。

示例(通过API调用验证数据)

考虑这样一个场景:您需要通过进行API调用来验证人员的ID。以下是您可以实现它的方法:

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Schema
Schema
,
import ParseResult
ParseResult
} from "effect"
// 定义进行API请求的函数
const
const get: (url: string) => Effect.Effect<unknown, Error>
get
= (
url: string
url
: string):
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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

Details

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

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

@since2.0.0

@since2.0.0

Effect
<unknown,
interface Error
Error
> =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const tryPromise: <unknown, Error>(options: {
readonly try: (signal: AbortSignal) => PromiseLike<unknown>;
readonly catch: (error: unknown) => Error;
}) => Effect.Effect<unknown, Error, never> (+1 overload)

Creates an Effect that represents an asynchronous computation that might fail.

When to Use

In situations where you need to perform asynchronous operations that might fail, such as fetching data from an API, you can use the tryPromise constructor. This constructor is designed to handle operations that could throw exceptions by capturing those exceptions and transforming them into manageable errors.

Error Handling

There are two ways to handle errors with tryPromise:

  1. If you don't provide a catch function, the error is caught and the effect fails with an UnknownException.
  2. If you provide a catch function, the error is caught and the catch function maps it to an error of type E.

Interruptions

An optional AbortSignal can be provided to allow for interruption of the wrapped Promise API.

Example (Fetching a TODO Item)

import { Effect } from "effect"
const getTodo = (id: number) =>
// Will catch any errors and propagate them as UnknownException
Effect.tryPromise(() =>
fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
)
// ┌─── Effect<Response, UnknownException, never>
// ▼
const program = getTodo(1)

Example (Custom Error Handling)

import { Effect } from "effect"
const getTodo = (id: number) =>
Effect.tryPromise({
try: () => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`),
// remap the error
catch: (unknown) => new Error(`something went wrong ${unknown}`)
})
// ┌─── Effect<Response, Error, never>
// ▼
const program = getTodo(1)

@seepromise if the effectful computation is asynchronous and does not throw errors.

@since2.0.0

tryPromise
({
try: (signal: AbortSignal) => PromiseLike<unknown>
try
: () =>
function fetch(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>
fetch
(
url: string
url
).
Promise<Response>.then<unknown, unknown>(onfulfilled?: ((value: Response) => unknown) | null | undefined, onrejected?: ((reason: any) => unknown) | null | undefined): Promise<unknown>

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

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

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

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

then
((
res: Response
res
) => {
if (
res: Response
res
.
Response.ok: boolean
ok
) {
return
res: Response
res
.
BodyMixin.json: () => Promise<unknown>
json
() as
interface Promise<T>

Represents the completion of an asynchronous operation

Promise
<unknown>
}
throw new
var Error: ErrorConstructor
new (message?: string) => Error
Error
(
var String: StringConstructor
(value?: any) => string

Allows manipulation and formatting of text strings and determination and location of substrings within strings.

String
(
res: Response
res
.
Response.status: number
status
))
}),
catch: (error: unknown) => Error
catch
: (
e: unknown
e
) => new
var Error: ErrorConstructor
new (message?: string) => Error
Error
(
var String: StringConstructor
(value?: any) => string

Allows manipulation and formatting of text strings and determination and location of substrings within strings.

String
(
e: unknown
e
))
})
// 为人员ID创建品牌模式
const
const PeopleId: Schema.brand<typeof Schema.String, "PeopleId">
PeopleId
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.brand<typeof Schema.String, "PeopleId">): Schema.brand<typeof Schema.String, "PeopleId"> (+21 overloads)
pipe
(
import Schema
Schema
.
const brand: <typeof Schema.String, "PeopleId">(brand: "PeopleId", annotations?: Schema.Annotations.Schema<string & Brand<"PeopleId">, readonly []> | undefined) => (self: typeof Schema.String) => Schema.brand<typeof Schema.String, "PeopleId">

Returns a nominal branded schema by applying a brand to a given schema.

Schema<A> + B -> Schema<A & Brand<B>>

@example

import * as Schema from "effect/Schema"
const Int = Schema.Number.pipe(Schema.int(), Schema.brand("Int"))
type Int = Schema.Schema.Type<typeof Int> // number & Brand<"Int">

@since3.10.0

brand
("PeopleId"))
// 定义带有异步转换的模式
const
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, never>
PeopleIdFromString
=
import Schema
Schema
.
const transformOrFail: <Schema.brand<typeof Schema.String, "PeopleId">, typeof Schema.String, never, never>(from: typeof Schema.String, to: Schema.brand<typeof Schema.String, "PeopleId">, options: {
readonly decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect.Effect<string, ParseResult.ParseIssue, never>;
readonly encode: (toI: string, options: ParseOptions, ast: Transformation, toA: string & Brand<...>) => Effect.Effect<...>;
readonly strict?: true;
} | {
...;
}) => Schema.transformOrFail<...> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided decoding functions.

@since3.10.0

transformOrFail
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
const PeopleId: Schema.brand<typeof Schema.String, "PeopleId">
PeopleId
,
{
strict?: true
strict
: true,
decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect.Effect<string, ParseResult.ParseIssue, never>
decode
: (
s: string
s
,
_: ParseOptions
_
,
ast: Transformation
ast
) =>
// 进行API调用以验证ID
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const mapBoth: <unknown, Error, never, ParseResult.Type, string>(self: Effect.Effect<unknown, Error, never>, options: {
readonly onFailure: (e: Error) => ParseResult.Type;
readonly onSuccess: (a: unknown) => string;
}) => Effect.Effect<string, ParseResult.Type, never> (+1 overload)

Applies transformations to both the success and error channels of an effect.

Details

This function takes two map functions as arguments: one for the error channel and one for the success channel. You can use it when you want to modify both the error and the success values without altering the overall success or failure status of the effect.

Example

import { Effect } from "effect"
// ┌─── Effect<number, string, never>
// ▼
const simulatedTask = Effect.fail("Oh no!").pipe(Effect.as(1))
// ┌─── Effect<boolean, Error, never>
// ▼
const modified = Effect.mapBoth(simulatedTask, {
onFailure: (message) => new Error(message),
onSuccess: (n) => n > 0
})

@seemap for a version that operates on the success channel.

@seemapError for a version that operates on the error channel.

@since2.0.0

mapBoth
(
const get: (url: string) => Effect.Effect<unknown, Error>
get
(`https://swapi.dev/api/people/${
s: string
s
}`), {
// 失败API调用的错误处理
onFailure: (e: Error) => ParseResult.Type
onFailure
: (
e: Error
e
) => new
import ParseResult
ParseResult
.
constructor Type(ast: AST, actual: unknown, message?: string | undefined): ParseResult.Type

The Type variant of the ParseIssue type represents an error that occurs when the actual value is not of the expected type. The ast field specifies the expected type, and the actual field contains the value that caused the error.

@since3.10.0

Type
(
ast: Transformation
ast
,
s: string
s
,
e: Error
e
.
Error.message: string
message
),
// 如果API调用成功则返回ID
onSuccess: (a: unknown) => string
onSuccess
: () =>
s: string
s
}),
encode: (toI: string, options: ParseOptions, ast: Transformation, toA: string & Brand<"PeopleId">) => Effect.Effect<string, ParseResult.ParseIssue, never>
encode
:
import ParseResult
ParseResult
.
const succeed: <A>(a: A) => Either<A, ParseResult.ParseIssue>

@since3.10.0

succeed
}
)
// ┌─── string
// ▼
type
type Encoded = string
Encoded
= typeof
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, never>
PeopleIdFromString
.
Schema<string & Brand<"PeopleId">, string, never>.Encoded: string
Encoded
// ┌─── string & Brand<"PeopleId">
// ▼
type
type Type = string & Brand<"PeopleId">
Type
= typeof
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, never>
PeopleIdFromString
.
Schema<string & Brand<"PeopleId">, string, never>.Type: string & Brand<"PeopleId">
Type
// ┌─── never
// ▼
type
type Context = never
Context
= typeof
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, never>
PeopleIdFromString
.
Schema<string & Brand<"PeopleId">, string, never>.Context: never
Context
// 运行成功的解码操作
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromiseExit: <string & Brand<"PeopleId">, ParseResult.ParseError>(effect: Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<string & Brand<"PeopleId">, ParseResult.ParseError>>

Runs an effect and returns a Promise that resolves to an Exit, representing the outcome.

Details

This function executes an effect and resolves to an Exit object. The Exit type provides detailed information about the result of the effect:

  • If the effect succeeds, the Exit will be of type Success and include the value produced by the effect.
  • If the effect fails, the Exit will be of type Failure and contain a Cause object, detailing the failure.

Using this function allows you to examine both successful results and failure cases in a unified way, while still leveraging Promise for handling the asynchronous behavior of the effect.

When to Use

Use this function when you need to understand the outcome of an effect, whether it succeeded or failed, and want to work with this result using Promise syntax. This is particularly useful when integrating with systems that rely on promises but need more detailed error handling than a simple rejection.

Example (Handling Results as Exit)

import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

@since2.0.0

runPromiseExit
(
import Schema
Schema
.
const decodeUnknown: <string & Brand<"PeopleId">, string, never>(schema: Schema.Schema<string & Brand<"PeopleId">, string, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>

@since3.10.0

decodeUnknown
(
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, never>
PeopleIdFromString
)("1")).
Promise<Exit<string & Brand<"PeopleId">, ParseError>>.then<void, never>(onfulfilled?: ((value: Exit<string & Brand<"PeopleId">, ParseResult.ParseError>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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

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

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

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

then
(
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
)
/*
输出:
{ _id: 'Exit', _tag: 'Success', value: '1' }
*/
// 运行将失败的解码操作
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromiseExit: <string & Brand<"PeopleId">, ParseResult.ParseError>(effect: Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<string & Brand<"PeopleId">, ParseResult.ParseError>>

Runs an effect and returns a Promise that resolves to an Exit, representing the outcome.

Details

This function executes an effect and resolves to an Exit object. The Exit type provides detailed information about the result of the effect:

  • If the effect succeeds, the Exit will be of type Success and include the value produced by the effect.
  • If the effect fails, the Exit will be of type Failure and contain a Cause object, detailing the failure.

Using this function allows you to examine both successful results and failure cases in a unified way, while still leveraging Promise for handling the asynchronous behavior of the effect.

When to Use

Use this function when you need to understand the outcome of an effect, whether it succeeded or failed, and want to work with this result using Promise syntax. This is particularly useful when integrating with systems that rely on promises but need more detailed error handling than a simple rejection.

Example (Handling Results as Exit)

import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

@since2.0.0

runPromiseExit
(
import Schema
Schema
.
const decodeUnknown: <string & Brand<"PeopleId">, string, never>(schema: Schema.Schema<string & Brand<"PeopleId">, string, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>

@since3.10.0

decodeUnknown
(
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, never>
PeopleIdFromString
)("fail")
).
Promise<Exit<string & Brand<"PeopleId">, ParseError>>.then<void, never>(onfulfilled?: ((value: Exit<string & Brand<"PeopleId">, ParseResult.ParseError>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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

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

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

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

then
(
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
)
/*
输出:
{
_id: 'Exit',
_tag: 'Failure',
cause: {
_id: 'Cause',
_tag: 'Fail',
failure: {
_id: 'ParseError',
message: '(string <-> string & Brand<"PeopleId">)\n' +
'└─ Transformation process failure\n' +
' └─ Error: 404'
}
}
}
*/

在您的转换依赖于外部服务的情况下,您可以在decodeencode函数中注入这些服务。然后在模式的Requirements通道中跟踪这些依赖项:

Schema<Type, Encoded, Requirements>

示例(使用服务验证数据)

import {
type Context = Validation

@since2.0.0

@since2.0.0

Context
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Schema
Schema
,
import ParseResult
ParseResult
,
import Layer
Layer
} from "effect"
// 定义用于依赖注入的验证服务
class
class Validation
Validation
extends
import Context

@since2.0.0

@since2.0.0

Context
.
const Tag: <"Validation">(id: "Validation") => <Self, Shape>() => Context.TagClass<Self, "Validation", Shape>

@example

import * as assert from "node:assert"
import { Context, Layer } from "effect"
class MyTag extends Context.Tag("MyTag")<
MyTag,
{ readonly myNum: number }
>() {
static Live = Layer.succeed(this, { myNum: 108 })
}

@since2.0.0

Tag
("Validation")<
class Validation
Validation
,
{
readonly
validatePeopleid: (s: string) => Effect.Effect<void, Error>
validatePeopleid
: (
s: string
s
: string) =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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

Details

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

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

@since2.0.0

@since2.0.0

Effect
<void,
interface Error
Error
>
}
>() {}
// 为人员ID创建品牌模式
const
const PeopleId: Schema.brand<typeof Schema.String, "PeopleId">
PeopleId
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.brand<typeof Schema.String, "PeopleId">): Schema.brand<typeof Schema.String, "PeopleId"> (+21 overloads)
pipe
(
import Schema
Schema
.
const brand: <typeof Schema.String, "PeopleId">(brand: "PeopleId", annotations?: Schema.Annotations.Schema<string & Brand<"PeopleId">, readonly []> | undefined) => (self: typeof Schema.String) => Schema.brand<typeof Schema.String, "PeopleId">

Returns a nominal branded schema by applying a brand to a given schema.

Schema<A> + B -> Schema<A & Brand<B>>

@example

import * as Schema from "effect/Schema"
const Int = Schema.Number.pipe(Schema.int(), Schema.brand("Int"))
type Int = Schema.Schema.Type<typeof Int> // number & Brand<"Int">

@since3.10.0

brand
("PeopleId"))
// 将字符串转换为经过验证的PeopleId,
// 使用外部验证服务
const
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, Validation>
PeopleIdFromString
=
import Schema
Schema
.
const transformOrFail: <Schema.brand<typeof Schema.String, "PeopleId">, typeof Schema.String, Validation, never>(from: typeof Schema.String, to: Schema.brand<typeof Schema.String, "PeopleId">, options: {
readonly decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect.Effect<string, ParseResult.ParseIssue, Validation>;
readonly encode: (toI: string, options: ParseOptions, ast: Transformation, toA: string & Brand<...>) => Effect.Effect<...>;
readonly strict?: true;
} | {
...;
}) => Schema.transformOrFail<...> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided decoding functions.

@since3.10.0

transformOrFail
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
const PeopleId: Schema.brand<typeof Schema.String, "PeopleId">
PeopleId
,
{
strict?: true
strict
: true,
decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect.Effect<string, ParseResult.ParseIssue, Validation>
decode
: (
s: string
s
,
_: ParseOptions
_
,
ast: Transformation
ast
) =>
// 使用注入的服务异步验证ID
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Context.Tag<Validation, {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}>> | YieldWrap<Effect.Effect<void, Error, never>>, string>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Context.Tag<Validation, {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}>> | YieldWrap<Effect.Effect<void, Error, never>>, string, never>) => Effect.Effect<...> (+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* () {
// 访问验证服务
const
const validator: {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}
validator
= yield*
class Validation
Validation
// 使用服务验证ID
yield*
const validator: {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}
validator
.
validatePeopleid: (s: string) => Effect.Effect<void, Error>
validatePeopleid
(
s: string
s
)
return
s: string
s
}).
Pipeable.pipe<Effect.Effect<string, Error, Validation>, Effect.Effect<string, ParseResult.Type, Validation>>(this: Effect.Effect<string, Error, Validation>, ab: (_: Effect.Effect<string, Error, Validation>) => Effect.Effect<string, ParseResult.Type, Validation>): Effect.Effect<string, ParseResult.Type, Validation> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const mapError: <Error, ParseResult.Type>(f: (e: Error) => ParseResult.Type) => <A, R>(self: Effect.Effect<A, Error, R>) => Effect.Effect<A, ParseResult.Type, R> (+1 overload)

Transforms or modifies the error produced by an effect without affecting its success value.

When to Use

This function is helpful when you want to enhance the error with additional information, change the error type, or apply custom error handling while keeping the original behavior of the effect's success values intact. It only operates on the error channel and leaves the success channel unchanged.

Example

import { Effect } from "effect"
// ┌─── Effect<number, string, never>
// ▼
const simulatedTask = Effect.fail("Oh no!").pipe(Effect.as(1))
// ┌─── Effect<number, Error, never>
// ▼
const mapped = Effect.mapError(
simulatedTask,
(message) => new Error(message)
)

@seemap for a version that operates on the success channel.

@seemapBoth for a version that operates on both channels.

@seeorElseFail if you want to replace the error with a new one.

@since2.0.0

mapError
((
e: Error
e
) => new
import ParseResult
ParseResult
.
constructor Type(ast: AST, actual: unknown, message?: string | undefined): ParseResult.Type

The Type variant of the ParseIssue type represents an error that occurs when the actual value is not of the expected type. The ast field specifies the expected type, and the actual field contains the value that caused the error.

@since3.10.0

Type
(
ast: Transformation
ast
,
s: string
s
,
e: Error
e
.
Error.message: string
message
))
),
encode: (toI: string, options: ParseOptions, ast: Transformation, toA: string & Brand<"PeopleId">) => Effect.Effect<string, ParseResult.ParseIssue, never>
encode
:
import ParseResult
ParseResult
.
const succeed: <A>(a: A) => Either<A, ParseResult.ParseIssue>

@since3.10.0

succeed
// 通过简单返回字符串进行编码
}
)
// ┌─── string
// ▼
type
type Encoded = string
Encoded
= typeof
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, Validation>
PeopleIdFromString
.
Schema<string & Brand<"PeopleId">, string, Validation>.Encoded: string
Encoded
// ┌─── string & Brand<"PeopleId">
// ▼
type
type Type = string & Brand<"PeopleId">
Type
= typeof
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, Validation>
PeopleIdFromString
.
Schema<string & Brand<"PeopleId">, string, Validation>.Type: string & Brand<"PeopleId">
Type
// ┌─── Validation
// ▼
type
type Context = Validation

@since2.0.0

@since2.0.0

Context
= typeof
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, Validation>
PeopleIdFromString
.
Schema<string & Brand<"PeopleId">, string, Validation>.Context: Validation
Context
// 提供成功验证服务的层
const
const SuccessTest: Layer.Layer<Validation, never, never>
SuccessTest
=
import Layer
Layer
.
const succeed: <Validation, {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}>(tag: Context.Tag<Validation, {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}>, resource: {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}) => Layer.Layer<Validation, never, never> (+1 overload)

Constructs a layer from the specified value.

@since2.0.0

succeed
(
class Validation
Validation
, {
validatePeopleid: (s: string) => Effect.Effect<void, Error>
validatePeopleid
: (
_: string
_
) =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const void: Effect.Effect<void, never, never>
export void

Represents an effect that does nothing and produces no value.

When to Use

Use this effect when you need to represent an effect that does nothing. This is useful in scenarios where you need to satisfy an effect-based interface or control program flow without performing any operations. For example, it can be used in situations where you want to return an effect from a function but do not need to compute or return any result.

@since2.0.0

void
})
// 运行成功的解码操作
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromiseExit: <string & Brand<"PeopleId">, ParseResult.ParseError>(effect: Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<string & Brand<"PeopleId">, ParseResult.ParseError>>

Runs an effect and returns a Promise that resolves to an Exit, representing the outcome.

Details

This function executes an effect and resolves to an Exit object. The Exit type provides detailed information about the result of the effect:

  • If the effect succeeds, the Exit will be of type Success and include the value produced by the effect.
  • If the effect fails, the Exit will be of type Failure and contain a Cause object, detailing the failure.

Using this function allows you to examine both successful results and failure cases in a unified way, while still leveraging Promise for handling the asynchronous behavior of the effect.

When to Use

Use this function when you need to understand the outcome of an effect, whether it succeeded or failed, and want to work with this result using Promise syntax. This is particularly useful when integrating with systems that rely on promises but need more detailed error handling than a simple rejection.

Example (Handling Results as Exit)

import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

@since2.0.0

runPromiseExit
(
import Schema
Schema
.
const decodeUnknown: <string & Brand<"PeopleId">, string, Validation>(schema: Schema.Schema<string & Brand<"PeopleId">, string, Validation>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, Validation>

@since3.10.0

decodeUnknown
(
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, Validation>
PeopleIdFromString
)("1").
Pipeable.pipe<Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, Validation>, Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>>(this: Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, Validation>, ab: (_: Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, Validation>) => Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const provide: <Validation, never, never>(layer: Layer.Layer<Validation, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Validation>> (+9 overloads)

Provides necessary dependencies to an effect, removing its environmental requirements.

Details

This function allows you to supply the required environment for an effect. The environment can be provided in the form of one or more Layers, a Context, a Runtime, or a ManagedRuntime. Once the environment is provided, the effect can run without requiring external dependencies.

You can compose layers to create a modular and reusable way of setting up the environment for effects. For example, layers can be used to configure databases, logging services, or any other required dependencies.

Example

import { Context, Effect, Layer } from "effect"
class Database extends Context.Tag("Database")<
Database,
{ readonly query: (sql: string) => Effect.Effect<Array<unknown>> }
>() {}
const DatabaseLive = Layer.succeed(
Database,
{
// Simulate a database query
query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([]))
}
)
// ┌─── Effect<unknown[], never, Database>
// ▼
const program = Effect.gen(function*() {
const database = yield* Database
const result = yield* database.query("SELECT * FROM users")
return result
})
// ┌─── Effect<unknown[], never, never>
// ▼
const runnable = Effect.provide(program, DatabaseLive)
Effect.runPromise(runnable).then(console.log)
// Output:
// timestamp=... level=INFO fiber=#0 message="Executing query: SELECT * FROM users"
// []

@seeprovideService for providing a service to an effect.

@since2.0.0

provide
(
const SuccessTest: Layer.Layer<Validation, never, never>
SuccessTest
)
)
).
Promise<Exit<string & Brand<"PeopleId">, ParseError>>.then<void, never>(onfulfilled?: ((value: Exit<string & Brand<"PeopleId">, ParseResult.ParseError>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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

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

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

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

then
(
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
)
/*
输出:
{ _id: 'Exit', _tag: 'Success', value: '1' }
*/
// 提供失败验证服务的层
const
const FailureTest: Layer.Layer<Validation, never, never>
FailureTest
=
import Layer
Layer
.
const succeed: <Validation, {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}>(tag: Context.Tag<Validation, {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}>, resource: {
readonly validatePeopleid: (s: string) => Effect.Effect<void, Error>;
}) => Layer.Layer<Validation, never, never> (+1 overload)

Constructs a layer from the specified value.

@since2.0.0

succeed
(
class Validation
Validation
, {
validatePeopleid: (s: string) => Effect.Effect<void, Error>
validatePeopleid
: (
_: string
_
) =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Creates an Effect that represents a recoverable error.

When to Use

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

catchAll

or

catchTag

.

Example (Creating a Failed Effect)

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

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

@since2.0.0

fail
(new
var Error: ErrorConstructor
new (message?: string) => Error
Error
("404"))
})
// 运行将失败的解码操作
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runPromiseExit: <string & Brand<"PeopleId">, ParseResult.ParseError>(effect: Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<Exit<string & Brand<"PeopleId">, ParseResult.ParseError>>

Runs an effect and returns a Promise that resolves to an Exit, representing the outcome.

Details

This function executes an effect and resolves to an Exit object. The Exit type provides detailed information about the result of the effect:

  • If the effect succeeds, the Exit will be of type Success and include the value produced by the effect.
  • If the effect fails, the Exit will be of type Failure and contain a Cause object, detailing the failure.

Using this function allows you to examine both successful results and failure cases in a unified way, while still leveraging Promise for handling the asynchronous behavior of the effect.

When to Use

Use this function when you need to understand the outcome of an effect, whether it succeeded or failed, and want to work with this result using Promise syntax. This is particularly useful when integrating with systems that rely on promises but need more detailed error handling than a simple rejection.

Example (Handling Results as Exit)

import { Effect } from "effect"
// Execute a successful effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.succeed(1)).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Success",
// value: 1
// }
// Execute a failing effect and get the Exit result as a Promise
Effect.runPromiseExit(Effect.fail("my error")).then(console.log)
// Output:
// {
// _id: "Exit",
// _tag: "Failure",
// cause: {
// _id: "Cause",
// _tag: "Fail",
// failure: "my error"
// }
// }

@since2.0.0

runPromiseExit
(
import Schema
Schema
.
const decodeUnknown: <string & Brand<"PeopleId">, string, Validation>(schema: Schema.Schema<string & Brand<"PeopleId">, string, Validation>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, Validation>

@since3.10.0

decodeUnknown
(
const PeopleIdFromString: Schema.transformOrFail<typeof Schema.String, Schema.brand<typeof Schema.String, "PeopleId">, Validation>
PeopleIdFromString
)("fail").
Pipeable.pipe<Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, Validation>, Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>>(this: Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, Validation>, ab: (_: Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, Validation>) => Effect.Effect<string & Brand<"PeopleId">, ParseResult.ParseError, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const provide: <Validation, never, never>(layer: Layer.Layer<Validation, never, never>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Validation>> (+9 overloads)

Provides necessary dependencies to an effect, removing its environmental requirements.

Details

This function allows you to supply the required environment for an effect. The environment can be provided in the form of one or more Layers, a Context, a Runtime, or a ManagedRuntime. Once the environment is provided, the effect can run without requiring external dependencies.

You can compose layers to create a modular and reusable way of setting up the environment for effects. For example, layers can be used to configure databases, logging services, or any other required dependencies.

Example

import { Context, Effect, Layer } from "effect"
class Database extends Context.Tag("Database")<
Database,
{ readonly query: (sql: string) => Effect.Effect<Array<unknown>> }
>() {}
const DatabaseLive = Layer.succeed(
Database,
{
// Simulate a database query
query: (sql: string) => Effect.log(`Executing query: ${sql}`).pipe(Effect.as([]))
}
)
// ┌─── Effect<unknown[], never, Database>
// ▼
const program = Effect.gen(function*() {
const database = yield* Database
const result = yield* database.query("SELECT * FROM users")
return result
})
// ┌─── Effect<unknown[], never, never>
// ▼
const runnable = Effect.provide(program, DatabaseLive)
Effect.runPromise(runnable).then(console.log)
// Output:
// timestamp=... level=INFO fiber=#0 message="Executing query: SELECT * FROM users"
// []

@seeprovideService for providing a service to an effect.

@since2.0.0

provide
(
const FailureTest: Layer.Layer<Validation, never, never>
FailureTest
)
)
).
Promise<Exit<string & Brand<"PeopleId">, ParseError>>.then<void, never>(onfulfilled?: ((value: Exit<string & Brand<"PeopleId">, ParseResult.ParseError>) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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

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

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

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

then
(
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
)
/*
输出:
{
_id: 'Exit',
_tag: 'Failure',
cause: {
_id: 'Cause',
_tag: 'Fail',
failure: {
_id: 'ParseError',
message: '(string <-> string & Brand<"PeopleId">)\n' +
'└─ Transformation process failure\n' +
' └─ Error: 404'
}
}
}
*/

在某些情况下,将值编码回其原始形式可能没有意义或不可取。您可以使用Schema.transformOrFail来定义单向转换,并在编码过程中显式返回Forbidden解析错误。这确保一旦值被转换,就无法恢复到其原始形式。

示例(禁止编码的密码哈希)

考虑这样一个场景:您需要对用户的明文密码进行哈希处理以进行安全存储。重要的是,哈希密码不能被逆转回明文。通过使用Schema.transformOrFail,您可以强制执行此限制,确保从明文到哈希密码的单向转换。

import {
import Schema
Schema
,
import ParseResult
ParseResult
,
import Redacted
Redacted
} from "effect"
import {
function createHash(algorithm: string, options?: HashOptions): Hash

Creates and returns a Hash object that can be used to generate hash digests using the given algorithm. Optional options argument controls stream behavior. For XOF hash functions such as 'shake256', the outputLength option can be used to specify the desired output length in bytes.

The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms will display the available digest algorithms.

Example: generating the sha256 sum of a file

import {
createReadStream,
} from 'node:fs';
import { argv } from 'node:process';
const {
createHash,
} = await import('node:crypto');
const filename = argv[2];
const hash = createHash('sha256');
const input = createReadStream(filename);
input.on('readable', () => {
// Only one element is going to be produced by the
// hash stream.
const data = input.read();
if (data)
hash.update(data);
else {
console.log(`${hash.digest('hex')} ${filename}`);
}
});

@sincev0.1.92

@paramoptions stream.transform options

createHash
} from "node:crypto"
// 定义明文密码的模式
// 具有最小长度要求
const
const PlainPassword: Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">
PlainPassword
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.filter<typeof Schema.String>, Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.filter<typeof Schema.String>, bc: (_: Schema.filter<typeof Schema.String>) => Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">): Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword"> (+21 overloads)
pipe
(
import Schema
Schema
.
const minLength: <typeof Schema.String>(minLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: typeof Schema.String & Schema.Schema<A, string, never>) => Schema.filter<typeof Schema.String>

@since3.10.0

minLength
(6),
import Schema
Schema
.
const brand: <Schema.filter<typeof Schema.String>, "PlainPassword">(brand: "PlainPassword", annotations?: Schema.Annotations.Schema<string & Brand<"PlainPassword">, readonly []> | undefined) => (self: Schema.filter<typeof Schema.String>) => Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">

Returns a nominal branded schema by applying a brand to a given schema.

Schema<A> + B -> Schema<A & Brand<B>>

@example

import * as Schema from "effect/Schema"
const Int = Schema.Number.pipe(Schema.int(), Schema.brand("Int"))
type Int = Schema.Schema.Type<typeof Int> // number & Brand<"Int">

@since3.10.0

brand
("PlainPassword", {
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.identifier?: string
identifier
: "PlainPassword" })
)
// 将哈希密码定义为单独的品牌类型模式
const
const HashedPassword: Schema.brand<typeof Schema.String, "HashedPassword">
HashedPassword
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.brand<typeof Schema.String, "HashedPassword">>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.brand<typeof Schema.String, "HashedPassword">): Schema.brand<typeof Schema.String, "HashedPassword"> (+21 overloads)
pipe
(
import Schema
Schema
.
const brand: <typeof Schema.String, "HashedPassword">(brand: "HashedPassword", annotations?: Schema.Annotations.Schema<string & Brand<"HashedPassword">, readonly []> | undefined) => (self: typeof Schema.String) => Schema.brand<typeof Schema.String, "HashedPassword">

Returns a nominal branded schema by applying a brand to a given schema.

Schema<A> + B -> Schema<A & Brand<B>>

@example

import * as Schema from "effect/Schema"
const Int = Schema.Number.pipe(Schema.int(), Schema.brand("Int"))
type Int = Schema.Schema.Type<typeof Int> // number & Brand<"Int">

@since3.10.0

brand
("HashedPassword", {
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.identifier?: string
identifier
: "HashedPassword" })
)
// 定义从明文密码到哈希密码的单向转换
export const
const PasswordHashing: Schema.transformOrFail<Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">, Schema.RedactedFromSelf<Schema.brand<typeof Schema.String, "HashedPassword">>, never>
PasswordHashing
=
import Schema
Schema
.
const transformOrFail: <Schema.RedactedFromSelf<Schema.brand<typeof Schema.String, "HashedPassword">>, Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">, never, never>(from: Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">, to: Schema.RedactedFromSelf<Schema.brand<typeof Schema.String, "HashedPassword">>, options: {
readonly decode: (fromA: string & Brand<"PlainPassword">, options: ParseOptions, ast: Transformation, fromI: string) => Effect<...>;
readonly encode: (toI: Redacted.Redacted<...>, options: ParseOptions, ast: Transformation, toA: Redacted.Redacted<...>) => Effect<...>;
readonly strict?: true;
} | {
...;
}) => Schema.transformOrFail<...> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided decoding functions.

@since3.10.0

transformOrFail
(
const PlainPassword: Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">
PlainPassword
,
// 将输出包装在Redacted中以增加安全性
import Schema
Schema
.
const RedactedFromSelf: <Schema.brand<typeof Schema.String, "HashedPassword">>(value: Schema.brand<typeof Schema.String, "HashedPassword">) => Schema.RedactedFromSelf<Schema.brand<typeof Schema.String, "HashedPassword">>

@since3.10.0

RedactedFromSelf
(
const HashedPassword: Schema.brand<typeof Schema.String, "HashedPassword">
HashedPassword
),
{
strict?: true
strict
: true,
// 解码:将明文密码转换为哈希密码
decode: (fromA: string & Brand<"PlainPassword">, options: ParseOptions, ast: Transformation, fromI: string) => Effect<Redacted.Redacted<string>, ParseResult.ParseIssue, never>
decode
: (
plainPassword: string & Brand<"PlainPassword">
plainPassword
) => {
const
const hash: string
hash
=
function createHash(algorithm: string, options?: HashOptions): Hash

Creates and returns a Hash object that can be used to generate hash digests using the given algorithm. Optional options argument controls stream behavior. For XOF hash functions such as 'shake256', the outputLength option can be used to specify the desired output length in bytes.

The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms will display the available digest algorithms.

Example: generating the sha256 sum of a file

import {
createReadStream,
} from 'node:fs';
import { argv } from 'node:process';
const {
createHash,
} = await import('node:crypto');
const filename = argv[2];
const hash = createHash('sha256');
const input = createReadStream(filename);
input.on('readable', () => {
// Only one element is going to be produced by the
// hash stream.
const data = input.read();
if (data)
hash.update(data);
else {
console.log(`${hash.digest('hex')} ${filename}`);
}
});

@sincev0.1.92

@paramoptions stream.transform options

createHash
("sha256")
.
Hash.update(data: BinaryLike): Hash (+1 overload)

Updates the hash content with the given data, the encoding of which is given in inputEncoding. If encoding is not provided, and the data is a string, an encoding of 'utf8' is enforced. If data is a Buffer, TypedArray, orDataView, then inputEncoding is ignored.

This can be called many times with new data as it is streamed.

@sincev0.1.92

@paraminputEncoding The encoding of the data string.

update
(
plainPassword: string & Brand<"PlainPassword">
plainPassword
)
.
Hash.digest(encoding: BinaryToTextEncoding): string (+1 overload)

Calculates the digest of all of the data passed to be hashed (using the hash.update() method). If encoding is provided a string will be returned; otherwise a Buffer is returned.

The Hash object can not be used again after hash.digest() method has been called. Multiple calls will cause an error to be thrown.

@sincev0.1.92

@paramencoding The encoding of the return value.

digest
("hex")
// 将哈希包装在Redacted中
return
import ParseResult
ParseResult
.
const succeed: <Redacted.Redacted<string>>(a: Redacted.Redacted<string>) => Either<Redacted.Redacted<string>, ParseResult.ParseIssue>

@since3.10.0

succeed
(
import Redacted
Redacted
.
const make: <string>(value: string) => Redacted.Redacted<string>

This function creates a Redacted<A> instance from a given value A, securely hiding its content.

@example

import { Redacted } from "effect"
const API_KEY = Redacted.make("1234567890")

@since3.3.0

make
(
const hash: string
hash
))
},
// 编码:禁止将哈希密码逆转回明文
encode: (toI: Redacted.Redacted<string>, options: ParseOptions, ast: Transformation, toA: Redacted.Redacted<string & Brand<"HashedPassword">>) => Effect<string & Brand<"PlainPassword">, ParseResult.ParseIssue, never>
encode
: (
hashedPassword: Redacted.Redacted<string>
hashedPassword
,
_: ParseOptions
_
,
ast: Transformation
ast
) =>
import ParseResult
ParseResult
.
const fail: (issue: ParseResult.ParseIssue) => Either<never, ParseResult.ParseIssue>

@since3.10.0

fail
(
new
import ParseResult
ParseResult
.
constructor Forbidden(ast: AST, actual: unknown, message?: string | undefined): ParseResult.Forbidden

The Forbidden variant of the ParseIssue type represents a forbidden operation, such as when encountering an Effect that is not allowed to execute (e.g., using runSync).

@since3.10.0

Forbidden
(
ast: Transformation
ast
,
hashedPassword: Redacted.Redacted<string>
hashedPassword
,
"禁止将哈希密码编码回明文。"
)
)
}
)
// ┌─── string
// ▼
type
type Encoded = string
Encoded
= typeof
const PasswordHashing: Schema.transformOrFail<Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">, Schema.RedactedFromSelf<Schema.brand<typeof Schema.String, "HashedPassword">>, never>
PasswordHashing
.
Schema<Redacted<string & Brand<"HashedPassword">>, string, never>.Encoded: string
Encoded
// ┌─── Redacted<string & Brand<"HashedPassword">>
// ▼
type
type Type = Redacted.Redacted<string & Brand<"HashedPassword">>
Type
= typeof
const PasswordHashing: Schema.transformOrFail<Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">, Schema.RedactedFromSelf<Schema.brand<typeof Schema.String, "HashedPassword">>, never>
PasswordHashing
.
Schema<Redacted<string & Brand<"HashedPassword">>, string, never>.Type: Redacted.Redacted<string & Brand<"HashedPassword">>
Type
// 示例:将明文密码解码为哈希密码
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 Schema
Schema
.
decodeUnknownSync<Redacted.Redacted<string & Brand<"HashedPassword">>, string>(schema: Schema.Schema<Redacted.Redacted<string & Brand<"HashedPassword">>, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => Redacted.Redacted<string & Brand<"HashedPassword">>
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const PasswordHashing: Schema.transformOrFail<Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">, Schema.RedactedFromSelf<Schema.brand<typeof Schema.String, "HashedPassword">>, never>
PasswordHashing
)("myPlainPassword123")
)
// 输出:<redacted>
// 示例:尝试将哈希密码编码回明文
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 Schema
Schema
.
encodeUnknownSync<Redacted.Redacted<string & Brand<"HashedPassword">>, string>(schema: Schema.Schema<Redacted.Redacted<string & Brand<"HashedPassword">>, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export encodeUnknownSync

@throwsParseError

@since3.10.0

encodeUnknownSync
(
const PasswordHashing: Schema.transformOrFail<Schema.brand<Schema.filter<typeof Schema.String>, "PlainPassword">, Schema.RedactedFromSelf<Schema.brand<typeof Schema.String, "HashedPassword">>, never>
PasswordHashing
)(
import Redacted
Redacted
.
const make: <string>(value: string) => Redacted.Redacted<string>

This function creates a Redacted<A> instance from a given value A, securely hiding its content.

@example

import { Redacted } from "effect"
const API_KEY = Redacted.make("1234567890")

@since3.3.0

make
("2ef2b7..."))
)
/*
抛出:
ParseError: (PlainPassword <-> Redacted(<redacted>))
└─ Transformation process failure
└─ (PlainPassword <-> Redacted(<redacted>))
└─ 禁止将哈希密码编码回明文。
*/

在复杂应用程序中经常需要组合和重用模式,Schema.compose组合器提供了一种有效的方法来实现这一点。使用Schema.compose,您可以将两个模式Schema<B, A, R1>Schema<C, B, R2>链接成单个模式Schema<C, A, R1 | R2>

示例(组合模式将分隔字符串解析为数字)

import {
import Schema
Schema
} from "effect"
// 将字符串按逗号分割为字符串数组的模式
//
// ┌─── Schema<readonly string[], string, never>
// ▼
const
const schema1: Schema.Schema<readonly string[], string, never>
schema1
=
import Schema
Schema
.
function asSchema<Schema.transform<Schema.SchemaClass<string, string, never>, Schema.Array$<typeof Schema.String>>>(schema: Schema.transform<Schema.SchemaClass<string, string, never>, Schema.Array$<typeof Schema.String>>): Schema.Schema<readonly string[], string, never>

@since3.10.0

asSchema
(
import Schema
Schema
.
const split: (separator: string) => Schema.transform<Schema.SchemaClass<string>, Schema.Array$<typeof Schema.String>>

Returns a schema that allows splitting a string into an array of strings.

@since3.10.0

split
(","))
// 将字符串数组转换为数字数组的模式
//
// ┌─── Schema<readonly number[], readonly string[], never>
// ▼
const
const schema2: Schema.Schema<readonly number[], readonly string[], never>
schema2
=
import Schema
Schema
.
function asSchema<Schema.Array$<typeof Schema.NumberFromString>>(schema: Schema.Array$<typeof Schema.NumberFromString>): Schema.Schema<readonly number[], readonly string[], never>

@since3.10.0

asSchema
(
import Schema
Schema
.
Array<typeof Schema.NumberFromString>(value: typeof Schema.NumberFromString): Schema.Array$<typeof Schema.NumberFromString>
export Array

@since3.10.0

Array
(
import Schema
Schema
.
class NumberFromString

This schema transforms a string into a number by parsing the string using the parse function of the effect/Number module.

It returns an error if the value can't be converted (for example when non-numeric characters are provided).

The following special string values are supported: "NaN", "Infinity", "-Infinity".

@since3.10.0

NumberFromString
))
// 组合模式,接受字符串,按逗号分割,
// 并将结果转换为数字数组
//
// ┌─── Schema<readonly number[], string, never>
// ▼
const
const ComposedSchema: Schema.Schema<readonly number[], string, never>
ComposedSchema
=
import Schema
Schema
.
function asSchema<Schema.transform<Schema.Schema<readonly string[], string, never>, Schema.Schema<readonly number[], readonly string[], never>>>(schema: Schema.transform<Schema.Schema<readonly string[], string, never>, Schema.Schema<readonly number[], readonly string[], never>>): Schema.Schema<readonly number[], string, never>

@since3.10.0

asSchema
(
import Schema
Schema
.
const compose: <Schema.Schema<readonly string[], string, never>, Schema.Schema<readonly number[], readonly string[], never>, readonly string[]>(from: Schema.Schema<readonly string[], string, never>, to: Schema.Schema<readonly number[], readonly string[], never>) => Schema.transform<Schema.Schema<readonly string[], string, never>, Schema.Schema<readonly number[], readonly string[], never>> (+7 overloads)

@since3.10.0

compose
(
const schema1: Schema.Schema<readonly string[], string, never>
schema1
,
const schema2: Schema.Schema<readonly number[], readonly string[], never>
schema2
))

在组合模式时,您可能遇到一个模式的输出与下一个模式的输入不完全匹配的情况,例如,如果您有Schema<R1, A, B>Schema<R2, C, D>,其中CB不同。为了处理这些情况,您可以使用{ strict: false }选项来放宽类型约束。

示例(在组合中使用非严格选项)

import {
import Schema
Schema
} from "effect"
// 没有`strict: false`选项,
// 此组合会引发TypeScript错误
import Schema
Schema
.
const compose: <Schema.Union<[typeof Schema.Null, Schema.Literal<["0"]>]>>(to: Schema.Union<[typeof Schema.Null, Schema.Literal<["0"]>]>, options?: {
readonly strict: true;
}) => <From>(from: From & Schema.Schema<"0" | null, Schema.Schema<in out A, in out I = A, out R = never>.Encoded<From>, Schema.Schema.Context<From>>) => Schema.transform<From, Schema.Union<[typeof Schema.Null, Schema.Literal<["0"]>]>> (+7 overloads)

@since3.10.0

compose
(
import Schema
Schema
.
function Union<[typeof Schema.Null, Schema.Literal<["0"]>]>(members_0: typeof Schema.Null, members_1: Schema.Literal<["0"]>): Schema.Union<[typeof Schema.Null, Schema.Literal<["0"]>]> (+3 overloads)

@since3.10.0

Union
(
import Schema
Schema
.
class Null

@since3.10.0

Null
,
import Schema
Schema
.
function Literal<["0"]>(literals_0: "0"): Schema.Literal<["0"]> (+2 overloads)

@since3.10.0

Literal
("0")),
Error ts(2769) ― No overload matches this call. The last overload gave the following error. Argument of type 'Union<[typeof Null, Literal<["0"]>]>' is not assignable to parameter of type 'Union<[typeof Null, Literal<["0"]>]> & Schema<string, "0" | null, never>'. Type 'Union<[typeof Null, Literal<["0"]>]>' is not assignable to type 'Schema<string, "0" | null, never>'. Types of property 'Type' are incompatible. Type 'string | null' is not assignable to type 'string'. Type 'null' is not assignable to type 'string'.
import Schema
Schema
.
class NumberFromString

This schema transforms a string into a number by parsing the string using the parse function of the effect/Number module.

It returns an error if the value can't be converted (for example when non-numeric characters are provided).

The following special string values are supported: "NaN", "Infinity", "-Infinity".

@since3.10.0

NumberFromString
)
// 使用`strict: false`允许类型灵活性
import Schema
Schema
.
const compose: <Schema.Union<[typeof Schema.Null, Schema.Literal<["0"]>]>, typeof Schema.NumberFromString>(from: Schema.Union<[typeof Schema.Null, Schema.Literal<["0"]>]>, to: typeof Schema.NumberFromString, options: {
readonly strict: false;
}) => Schema.transform<Schema.Union<[typeof Schema.Null, Schema.Literal<["0"]>]>, typeof Schema.NumberFromString> (+7 overloads)

@since3.10.0

compose
(
import Schema
Schema
.
function Union<[typeof Schema.Null, Schema.Literal<["0"]>]>(members_0: typeof Schema.Null, members_1: Schema.Literal<["0"]>): Schema.Union<[typeof Schema.Null, Schema.Literal<["0"]>]> (+3 overloads)

@since3.10.0

Union
(
import Schema
Schema
.
class Null

@since3.10.0

Null
,
import Schema
Schema
.
function Literal<["0"]>(literals_0: "0"): Schema.Literal<["0"]> (+2 overloads)

@since3.10.0

Literal
("0")),
import Schema
Schema
.
class NumberFromString

This schema transforms a string into a number by parsing the string using the parse function of the effect/Number module.

It returns an error if the value can't be converted (for example when non-numeric characters are provided).

The following special string values are supported: "NaN", "Infinity", "-Infinity".

@since3.10.0

NumberFromString
,
{
strict: false
strict
: false }
)

Schema.filterEffect函数启用需要异步或动态场景的验证,使其适用于涉及网络请求或数据库查询等副作用的验证情况。对于简单的同步验证,请参阅Schema.filter

示例(异步用户名验证)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Schema
Schema
} from "effect"
// 模拟异步函数来验证用户名
async function
function validateUsername(username: string): Promise<boolean>
validateUsername
(
username: string
username
: string) {
return
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
.
PromiseConstructor.resolve<boolean>(value: boolean): Promise<boolean> (+2 overloads)

Creates a new resolved promise for the provided value.

@paramvalue A promise.

@returnsA promise whose internal state matches the provided promise.

resolve
(
username: string
username
=== "gcanti")
}
// 定义带有有效果过滤器的模式
const
const ValidUsername: Schema.transformOrFail<typeof Schema.String, Schema.SchemaClass<string, string, never>, never>
ValidUsername
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.filterEffect<typeof Schema.String, never>>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.filterEffect<typeof Schema.String, never>): Schema.filterEffect<typeof Schema.String, never> (+21 overloads)
pipe
(
import Schema
Schema
.
const filterEffect: <typeof Schema.String, never>(f: (a: string, options: ParseOptions, self: Transformation) => Effect.Effect<FilterReturnType, never, never>) => (self: typeof Schema.String) => Schema.filterEffect<typeof Schema.String, never> (+1 overload)

@since3.10.0

filterEffect
((
username: string
username
) =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const promise: <string | boolean | Type | Missing | Unexpected | Forbidden | Pointer | Refinement | Transformation | Composite | Schema.FilterIssue | readonly Schema.FilterOutput[] | undefined>(evaluate: (signal: AbortSignal) => PromiseLike<string | boolean | Type | Missing | Unexpected | Forbidden | Pointer | Refinement | Transformation | Composite | Schema.FilterIssue | readonly Schema.FilterOutput[] | undefined>) => Effect.Effect<...>

Creates an Effect that represents an asynchronous computation guaranteed to succeed.

Details

The provided function (thunk) returns a Promise that should never reject; if it does, the error will be treated as a "defect".

This defect is not a standard error but indicates a flaw in the logic that was expected to be error-free. You can think of it similar to an unexpected crash in the program, which can be further managed or logged using tools like

catchAllDefect

.

Interruptions

An optional AbortSignal can be provided to allow for interruption of the wrapped Promise API.

When to Use

Use this function when you are sure the operation will not reject.

Example (Delayed Message)

import { Effect } from "effect"
const delay = (message: string) =>
Effect.promise<string>(
() =>
new Promise((resolve) => {
setTimeout(() => {
resolve(message)
}, 2000)
})
)
// ┌─── Effect<string, never, never>
// ▼
const program = delay("Async operation completed successfully!")

@seetryPromise for a version that can handle failures.

@since2.0.0

promise
(() =>
// 异步验证用户名,
// 如果无效则返回错误消息
function validateUsername(username: string): Promise<boolean>
validateUsername
(
username: string
username
).
Promise<boolean>.then<true | "Invalid username", string | boolean | Type | Missing | Unexpected | Forbidden | Pointer | Refinement | Transformation | Composite | Schema.FilterIssue | readonly Schema.FilterOutput[] | undefined>(onfulfilled?: ((value: boolean) => true | "Invalid username" | PromiseLike<true | "Invalid username">) | null | undefined, onrejected?: ((reason: any) => string | boolean | Type | Missing | Unexpected | ... 8 more ... | undefined) | null | undefined): Promise<...>

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

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

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

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

then
(
(
valid: boolean
valid
) =>
valid: boolean
valid
|| "Invalid username"
)
)
)
).
Annotable<transformOrFail<typeof String$, SchemaClass<string, string, never>, never>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.transformOrFail<typeof Schema.String, Schema.SchemaClass<string, string, never>, never>

Merges a set of new annotations with existing ones, potentially overwriting any duplicates.

annotations
({
Annotations.Schema<string, readonly []>.identifier?: string
identifier
: "ValidUsername" })
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

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

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

When to Use

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

Example (Running a Successful Effect as a Promise)

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

Example (Handling a Failing Effect as a Rejected Promise)

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

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

@since2.0.0

runPromise
(
import Schema
Schema
.
const decodeUnknown: <string, string, never>(schema: Schema.Schema<string, string, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Effect.Effect<string, ParseError, never>

@since3.10.0

decodeUnknown
(
const ValidUsername: Schema.transformOrFail<typeof Schema.String, Schema.SchemaClass<string, string, never>, never>
ValidUsername
)("xxx")).
Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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

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

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

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

then
(
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
)
/*
ParseError: ValidUsername
└─ Transformation process failure
└─ Invalid username
*/

按指定分隔符将字符串分割为子字符串数组。

示例(按逗号分割字符串)

import {
import Schema
Schema
} from "effect"
const
const schema: Schema.transform<Schema.SchemaClass<string, string, never>, Schema.Array$<typeof Schema.String>>
schema
=
import Schema
Schema
.
const split: (separator: string) => Schema.transform<Schema.SchemaClass<string>, Schema.Array$<typeof Schema.String>>

Returns a schema that allows splitting a string into an array of strings.

@since3.10.0

split
(",")
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => readonly string[]
decode
=
import Schema
Schema
.
decodeUnknownSync<readonly string[], string>(schema: Schema.Schema<readonly string[], string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => readonly string[]
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.transform<Schema.SchemaClass<string, string, never>, Schema.Array$<typeof Schema.String>>
schema
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => readonly string[]
decode
("")) // [""]
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 decode: (u: unknown, overrideOptions?: ParseOptions) => readonly string[]
decode
(",")) // ["", ""]
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 decode: (u: unknown, overrideOptions?: ParseOptions) => readonly string[]
decode
("a,")) // ["a", ""]
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 decode: (u: unknown, overrideOptions?: ParseOptions) => readonly string[]
decode
("a,b")) // ["a", "b"]

从字符串的开头和结尾删除空格。

示例(修剪空格)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
=
import Schema
Schema
.
decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class Trim

This schema allows removing whitespaces from the beginning and end of a string.

@since3.10.0

Trim
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("a")) // "a"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" a")) // "a"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("a ")) // "a"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" a ")) // "a"

将字符串转换为小写。

示例(转换为小写)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
=
import Schema
Schema
.
decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class Lowercase

This schema converts a string to lowercase.

@since3.10.0

Lowercase
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("A")) // "a"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" AB")) // " ab"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("Ab ")) // "ab "
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" ABc ")) // " abc "

将字符串转换为大写。

示例(转换为大写)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
=
import Schema
Schema
.
decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class Uppercase

This schema converts a string to uppercase.

@since3.10.0

Uppercase
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("a")) // "A"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" ab")) // " AB"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("aB ")) // "AB "
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" abC ")) // " ABC "

将字符串的第一个字符转换为大写。

示例(首字母大写字符串)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
=
import Schema
Schema
.
decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class Capitalize

This schema converts a string to capitalized one.

@since3.10.0

Capitalize
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("aa")) // "Aa"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" ab")) // " ab"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("aB ")) // "AB "
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" abC ")) // " abC "

将字符串的第一个字符转换为小写。

示例(首字母小写字符串)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
=
import Schema
Schema
.
decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class Uncapitalize

This schema converts a string to uncapitalized one.

@since3.10.0

Uncapitalize
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("AA")) // "aA"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" AB")) // " AB"
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("Ab ")) // "ab "
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(" AbC ")) // " AbC "

Schema.parseJson构造函数提供了一种使用JSON.parse的底层功能将JSON字符串转换为unknown类型的方法。 它还使用JSON.stringify进行编码。

示例(解析JSON字符串)

import {
import Schema
Schema
} from "effect"
const
const schema: Schema.SchemaClass<unknown, string, never>
schema
=
import Schema
Schema
.
const parseJson: (options?: Schema.ParseJsonOptions) => Schema.SchemaClass<unknown, string> (+1 overload)

The ParseJson combinator provides a method to convert JSON strings into the unknown type using the underlying functionality of JSON.parse. It also utilizes JSON.stringify for encoding.

You can optionally provide a ParseJsonOptions to configure both JSON.parse and JSON.stringify executions.

Optionally, you can pass a schema Schema<A, I, R> to obtain an A type instead of unknown.

@example

import * as assert from "node:assert"
import * as Schema from "effect/Schema"
assert.deepStrictEqual(Schema.decodeUnknownSync(Schema.parseJson())(`{"a":"1"}`), { a: "1" })
assert.deepStrictEqual(Schema.decodeUnknownSync(Schema.parseJson(Schema.Struct({ a: Schema.NumberFromString })))(`{"a":"1"}`), { a: 1 })

@since3.10.0

parseJson
()
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => unknown
decode
=
import Schema
Schema
.
decodeUnknownSync<unknown, string>(schema: Schema.Schema<unknown, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => unknown
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.SchemaClass<unknown, string, never>
schema
)
// 解析有效的JSON字符串
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 decode: (u: unknown, overrideOptions?: ParseOptions) => unknown
decode
("{}")) // 输出:{}
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 decode: (u: unknown, overrideOptions?: ParseOptions) => unknown
decode
(`{"a":"b"}`)) // 输出:{ a: "b" }
// 尝试解码空字符串会导致错误
const decode: (u: unknown, overrideOptions?: ParseOptions) => unknown
decode
("")
/*
抛出:
ParseError: (JsonString <-> unknown)
└─ Transformation process failure
└─ Unexpected end of JSON input
*/

为了进一步细化JSON解析的结果,您可以向Schema.parseJson构造函数提供模式。此模式将验证解析的JSON是否匹配特定结构。

示例(带结构验证的JSON解析)

在此示例中,Schema.parseJson使用结构模式来确保解析的JSON是具有数字属性a的对象。这为解析的数据添加了验证,确认它遵循预期的结构。

import {
import Schema
Schema
} from "effect"
// ┌─── SchemaClass<{ readonly a: number; }, string, never>
// ▼
const
const schema: Schema.transform<Schema.SchemaClass<unknown, string, never>, Schema.Struct<{
a: typeof Schema.Number;
}>>
schema
=
import Schema
Schema
.
const parseJson: <Schema.Struct<{
a: typeof Schema.Number;
}>>(schema: Schema.Struct<{
a: typeof Schema.Number;
}>, options?: Schema.ParseJsonOptions) => Schema.transform<Schema.SchemaClass<unknown, string, never>, Schema.Struct<{
a: typeof Schema.Number;
}>> (+1 overload)

The ParseJson combinator provides a method to convert JSON strings into the unknown type using the underlying functionality of JSON.parse. It also utilizes JSON.stringify for encoding.

You can optionally provide a ParseJsonOptions to configure both JSON.parse and JSON.stringify executions.

Optionally, you can pass a schema Schema<A, I, R> to obtain an A type instead of unknown.

@example

import * as assert from "node:assert"
import * as Schema from "effect/Schema"
assert.deepStrictEqual(Schema.decodeUnknownSync(Schema.parseJson())(`{"a":"1"}`), { a: "1" })
assert.deepStrictEqual(Schema.decodeUnknownSync(Schema.parseJson(Schema.Struct({ a: Schema.NumberFromString })))(`{"a":"1"}`), { a: 1 })

@since3.10.0

parseJson
(
import Schema
Schema
.
function Struct<{
a: typeof Schema.Number;
}>(fields: {
a: typeof Schema.Number;
}): Schema.Struct<{
a: typeof Schema.Number;
}> (+1 overload)

@since3.10.0

Struct
({
a: typeof Schema.Number
a
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
}))

将base64(RFC4648)编码的字符串解码为UTF-8字符串。

示例(解码Base64)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
=
import Schema
Schema
.
decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
const StringFromBase64: Schema.Schema<string, string, never>

Decodes a base64 (RFC4648) encoded string into a UTF-8 string.

@since3.10.0

StringFromBase64
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("Zm9vYmFy"))
// 输出:"foobar"

将base64(URL)编码的字符串解码为UTF-8字符串。

示例(解码Base64 URL)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
=
import Schema
Schema
.
decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
const StringFromBase64Url: Schema.Schema<string, string, never>

Decodes a base64 (URL) encoded string into a UTF-8 string.

@since3.10.0

StringFromBase64Url
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("Zm9vYmFy"))
// 输出:"foobar"

将十六进制编码的字符串解码为UTF-8字符串。

示例(解码十六进制字符串)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
=
import Schema
Schema
.
decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
const StringFromHex: Schema.Schema<string, string, never>

Decodes a hex encoded string into a UTF-8 string.

@since3.10.0

StringFromHex
)
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
(new
var TextEncoder: new () => TextEncoder

TextEncoder class is a global reference for import { TextEncoder } from 'node:util' https://nodejs.org/api/globals.html#textencoder

@sincev11.0.0

TextEncoder
().
TextEncoder.encode(input?: string): Uint8Array

UTF-8 encodes the input string and returns a Uint8Array containing the encoded bytes.

@paraminput The text to encode.

encode
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("0001020304050607")))
/*
输出:
Uint8Array(8) [
0, 1, 2, 3,
4, 5, 6, 7
]
*/

将URI编码的字符串解码为UTF-8字符串。它对于在URL中编码和解码数据很有用。

示例(解码URI组件)

import {
import Schema
Schema
} from "effect"
const
const PaginationSchema: Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>
PaginationSchema
=
import Schema
Schema
.
function Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>(fields: {
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}): Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}> (+1 overload)

@since3.10.0

Struct
({
maxItemPerPage: typeof Schema.Number
maxItemPerPage
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
page: typeof Schema.Number
page
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
const
const UrlSchema: Schema.transform<Schema.transformOrFail<Schema.SchemaClass<string, string, never>, typeof Schema.String, never>, Schema.transform<Schema.SchemaClass<unknown, string, never>, Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>>>
UrlSchema
=
import Schema
Schema
.
const compose: <Schema.transformOrFail<Schema.SchemaClass<string, string, never>, typeof Schema.String, never>, Schema.transform<Schema.SchemaClass<unknown, string, never>, Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>>, string>(from: Schema.transformOrFail<Schema.SchemaClass<string, string, never>, typeof Schema.String, never>, to: Schema.transform<Schema.SchemaClass<unknown, string, never>, Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>> & Schema.Schema<...>) => Schema.transform<...> (+7 overloads)

@since3.10.0

compose
(
import Schema
Schema
.
const StringFromUriComponent: Schema.transformOrFail<Schema.SchemaClass<string, string, never>, typeof Schema.String, never>

Decodes a URI component encoded string into a UTF-8 string. Can be used to store data in a URL.

@example

import { Schema } from "effect"
const PaginationSchema = Schema.Struct({
maxItemPerPage: Schema.Number,
page: Schema.Number
})
const UrlSchema = Schema.compose(Schema.StringFromUriComponent, Schema.parseJson(PaginationSchema))
console.log(Schema.encodeSync(UrlSchema)({ maxItemPerPage: 10, page: 1 }))
// Output: %7B%22maxItemPerPage%22%3A10%2C%22page%22%3A1%7D

@since3.12.0

StringFromUriComponent
,
import Schema
Schema
.
const parseJson: <Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>>(schema: Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>, options?: Schema.ParseJsonOptions) => Schema.transform<Schema.SchemaClass<unknown, string, never>, Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>> (+1 overload)

The ParseJson combinator provides a method to convert JSON strings into the unknown type using the underlying functionality of JSON.parse. It also utilizes JSON.stringify for encoding.

You can optionally provide a ParseJsonOptions to configure both JSON.parse and JSON.stringify executions.

Optionally, you can pass a schema Schema<A, I, R> to obtain an A type instead of unknown.

@example

import * as assert from "node:assert"
import * as Schema from "effect/Schema"
assert.deepStrictEqual(Schema.decodeUnknownSync(Schema.parseJson())(`{"a":"1"}`), { a: "1" })
assert.deepStrictEqual(Schema.decodeUnknownSync(Schema.parseJson(Schema.Struct({ a: Schema.NumberFromString })))(`{"a":"1"}`), { a: 1 })

@since3.10.0

parseJson
(
const PaginationSchema: Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>
PaginationSchema
)
)
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 Schema
Schema
.
encodeSync<{
readonly maxItemPerPage: number;
readonly page: number;
}, string>(schema: Schema.Schema<{
readonly maxItemPerPage: number;
readonly page: number;
}, string, never>, options?: ParseOptions): (a: {
readonly maxItemPerPage: number;
readonly page: number;
}, overrideOptions?: ParseOptions) => string
export encodeSync

@since3.10.0

encodeSync
(
const UrlSchema: Schema.transform<Schema.transformOrFail<Schema.SchemaClass<string, string, never>, typeof Schema.String, never>, Schema.transform<Schema.SchemaClass<unknown, string, never>, Schema.Struct<{
maxItemPerPage: typeof Schema.Number;
page: typeof Schema.Number;
}>>>
UrlSchema
)({
maxItemPerPage: number
maxItemPerPage
: 10,
page: number
page
: 1 }))
// 输出:%7B%22maxItemPerPage%22%3A10%2C%22page%22%3A1%7D

通过使用effect/Number模块的parse函数解析字符串,将字符串转换为数字。

如果值无法转换(例如提供非数字字符时),它会返回错误。

支持以下特殊字符串值:“NaN”、“Infinity”、“-Infinity”。

示例(从字符串解析数字)

import {
import Schema
Schema
} from "effect"
const
const schema: typeof Schema.NumberFromString
schema
=
import Schema
Schema
.
class NumberFromString

This schema transforms a string into a number by parsing the string using the parse function of the effect/Number module.

It returns an error if the value can't be converted (for example when non-numeric characters are provided).

The following special string values are supported: "NaN", "Infinity", "-Infinity".

@since3.10.0

NumberFromString
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
=
import Schema
Schema
.
decodeUnknownSync<number, string>(schema: Schema.Schema<number, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => number
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: typeof Schema.NumberFromString
schema
)
// 成功案例
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 decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("1")) // 1
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("-1")) // -1
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("1.5")) // 1.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
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("NaN")) // NaN
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 decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("Infinity")) // Infinity
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 decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("-Infinity")) // -Infinity
// 失败案例
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("a")
/*
抛出:
ParseError: NumberFromString
└─ Transformation process failure
└─ Expected NumberFromString, actual "a"
*/

将数字限制在指定范围内。

示例(限制数字)

import {
import Schema
Schema
} from "effect"
// 将输入限制在-1 <= x <= 1
const
const schema: Schema.transform<typeof Schema.Number, Schema.filter<Schema.SchemaClass<number, number, never>>>
schema
=
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
.
Pipeable.pipe<typeof Schema.Number, Schema.transform<typeof Schema.Number, Schema.filter<Schema.SchemaClass<number, number, never>>>>(this: typeof Schema.Number, ab: (_: typeof Schema.Number) => Schema.transform<typeof Schema.Number, Schema.filter<Schema.SchemaClass<number, number, never>>>): Schema.transform<typeof Schema.Number, Schema.filter<Schema.SchemaClass<number, number, never>>> (+21 overloads)
pipe
(
import Schema
Schema
.
const clamp: (minimum: number, maximum: number) => <S extends Schema.Schema<in out A, in out I = A, out R = never>.Any, A extends number>(self: S & Schema.Schema<A, Schema.Schema.Encoded<S>, Schema.Schema.Context<S>>) => Schema.transform<S, Schema.filter<Schema.SchemaClass<A>>>

Clamps a number between a minimum and a maximum value.

@since3.10.0

clamp
(-1, 1))
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
=
import Schema
Schema
.
decodeUnknownSync<number, number>(schema: Schema.Schema<number, number, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => number
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.transform<typeof Schema.Number, Schema.filter<Schema.SchemaClass<number, number, never>>>
schema
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
(-3)) // -1
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
(0)) // 0
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 decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
(3)) // 1

通过使用effect/Number模块的parse函数解析字符串,将字符串转换为数字。

如果值无法转换(例如提供非数字字符时),它会返回错误。

支持以下特殊字符串值:“NaN”、“Infinity”、“-Infinity”。

示例(解析和验证数字)

import {
import Schema
Schema
} from "effect"
const
const schema: Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never>
schema
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never>>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never>): Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never> (+21 overloads)
pipe
(
import Schema
Schema
.
function parseNumber<S extends Schema.Schema<in out A, in out I = A, out R = never>.Any, A extends string>(self: S & Schema.Schema<A, Schema.Schema.Encoded<S>, Schema.Schema.Context<S>>): Schema.transformOrFail<S, typeof Schema.Number>

Transforms a string into a number by parsing the string using the parse function of the effect/Number module.

It returns an error if the value can't be converted (for example when non-numeric characters are provided).

The following special string values are supported: "NaN", "Infinity", "-Infinity".

@since3.10.0

parseNumber
)
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
=
import Schema
Schema
.
decodeUnknownSync<number, string>(schema: Schema.Schema<number, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => number
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.transformOrFail<typeof Schema.String, typeof Schema.Number, never>
schema
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("1")) // 1
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("Infinity")) // Infinity
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 decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("NaN")) // NaN
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 decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("-"))
/*
抛出
ParseError: (string <-> number)
└─ Transformation process failure
└─ Expected (string <-> number), actual "-"
*/

对布尔值取反。

示例(布尔值取反)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => boolean
decode
=
import Schema
Schema
.
decodeUnknownSync<boolean, boolean>(schema: Schema.Schema<boolean, boolean, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => boolean
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class Not

@since3.10.0

Not
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => boolean
decode
(true)) // 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 decode: (u: unknown, overrideOptions?: ParseOptions) => boolean
decode
(false)) // true

使用Symbol.for将字符串转换为符号。

示例(从字符串创建符号)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => symbol
decode
=
import Schema
Schema
.
decodeUnknownSync<symbol, string>(schema: Schema.Schema<symbol, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => symbol
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class Symbol
export Symbol

Converts a string key into a globally shared symbol.

@since3.10.0

Symbol
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => symbol
decode
("a")) // Symbol(a)

使用BigInt构造函数将字符串转换为BigInt

示例(从字符串解析BigInt)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
=
import Schema
Schema
.
decodeUnknownSync<bigint, string>(schema: Schema.Schema<bigint, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => bigint
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class BigInt
export BigInt

This schema transforms a string into a bigint by parsing the string using the BigInt function.

It returns an error if the value can't be converted (for example when non-numeric characters are provided).

@since3.10.0

BigInt
)
// 成功案例
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 decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
("1")) // 1n
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 decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
("-1")) // -1n
// 失败案例
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
("a")
/*
抛出:
ParseError: bigint
└─ Transformation process failure
└─ Expected bigint, actual "a"
*/
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
("1.5") // 抛出
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
("NaN") // 抛出
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
("Infinity") // 抛出
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
("-Infinity") // 抛出

使用BigInt构造函数将数字转换为BigInt

示例(从数字解析BigInt)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
=
import Schema
Schema
.
decodeUnknownSync<bigint, number>(schema: Schema.Schema<bigint, number, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => bigint
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class BigIntFromNumber

This schema transforms a number into a bigint by parsing the number using the BigInt function.

It returns an error if the value can't be safely encoded as a number due to being out of range.

@since3.10.0

BigIntFromNumber
)
const
const encode: (a: bigint, overrideOptions?: ParseOptions) => number
encode
=
import Schema
Schema
.
encodeSync<bigint, number>(schema: Schema.Schema<bigint, number, never>, options?: ParseOptions): (a: bigint, overrideOptions?: ParseOptions) => number
export encodeSync

@since3.10.0

encodeSync
(
import Schema
Schema
.
class BigIntFromNumber

This schema transforms a number into a bigint by parsing the number using the BigInt function.

It returns an error if the value can't be safely encoded as a number due to being out of range.

@since3.10.0

BigIntFromNumber
)
// 成功案例
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 decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
(1)) // 1n
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 decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
(-1)) // -1n
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 encode: (a: bigint, overrideOptions?: ParseOptions) => number
encode
(1n)) // 1
var console: Console

The console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.

The module exports two specific components:

  • A Console class with methods such as console.log(), console.error() and console.warn() that can be used to write to any Node.js stream.
  • A global console instance configured to write to process.stdout and process.stderr. The global console can be used without importing the node:console module.

Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.

Example using the global console:

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

Example using the Console class:

const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err

@seesource

console
.
Console.log(message?: any, ...optionalParams: any[]): void

Prints to stdout with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).

const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout

See util.format() for more information.

@sincev0.1.100

log
(
const encode: (a: bigint, overrideOptions?: ParseOptions) => number
encode
(-1n)) // -1
// 失败案例
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
(1.5)
/*
抛出:
ParseError: BigintFromNumber
└─ Transformation process failure
└─ Expected BigintFromNumber, actual 1.5
*/
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
(
var NaN: number
NaN
) // 抛出
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
(
var Infinity: number
Infinity
) // 抛出
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
(-
var Infinity: number
Infinity
) // 抛出
const encode: (a: bigint, overrideOptions?: ParseOptions) => number
encode
(
var BigInt: BigIntConstructor
(value: bigint | boolean | number | string) => bigint
BigInt
(
var Number: NumberConstructor

An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.

Number
.
NumberConstructor.MAX_SAFE_INTEGER: number

The value of the largest integer n such that n and n + 1 are both exactly representable as a Number value. The value of Number.MAX_SAFE_INTEGER is 9007199254740991 2^53 − 1.

MAX_SAFE_INTEGER
) + 1n) // 抛出
const encode: (a: bigint, overrideOptions?: ParseOptions) => number
encode
(
var BigInt: BigIntConstructor
(value: bigint | boolean | number | string) => bigint
BigInt
(
var Number: NumberConstructor

An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers.

Number
.
NumberConstructor.MIN_SAFE_INTEGER: number

The value of the smallest integer n such that n and n − 1 are both exactly representable as a Number value. The value of Number.MIN_SAFE_INTEGER is −9007199254740991 (−(2^53 − 1)).

MIN_SAFE_INTEGER
) - 1n) // 抛出

BigInt限制在指定范围内。

示例(限制BigInt)

import {
import Schema
Schema
} from "effect"
// 将输入限制在-1n <= x <= 1n
const
const schema: Schema.transform<typeof Schema.BigIntFromSelf, Schema.filter<Schema.SchemaClass<bigint, bigint, never>>>
schema
=
import Schema
Schema
.
class BigIntFromSelf

@since3.10.0

BigIntFromSelf
.
Pipeable.pipe<typeof Schema.BigIntFromSelf, Schema.transform<typeof Schema.BigIntFromSelf, Schema.filter<Schema.SchemaClass<bigint, bigint, never>>>>(this: typeof Schema.BigIntFromSelf, ab: (_: typeof Schema.BigIntFromSelf) => Schema.transform<typeof Schema.BigIntFromSelf, Schema.filter<Schema.SchemaClass<bigint, bigint, never>>>): Schema.transform<typeof Schema.BigIntFromSelf, Schema.filter<Schema.SchemaClass<bigint, bigint, never>>> (+21 overloads)
pipe
(
import Schema
Schema
.
const clampBigInt: (minimum: bigint, maximum: bigint) => <S extends Schema.Schema<in out A, in out I = A, out R = never>.Any, A extends bigint>(self: S & Schema.Schema<A, Schema.Schema.Encoded<S>, Schema.Schema.Context<S>>) => Schema.transform<S, Schema.filter<Schema.SchemaClass<A>>>

Clamps a bigint between a minimum and a maximum value.

@since3.10.0

clampBigInt
(-1n, 1n))
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
=
import Schema
Schema
.
decodeUnknownSync<bigint, bigint>(schema: Schema.Schema<bigint, bigint, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => bigint
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.transform<typeof Schema.BigIntFromSelf, Schema.filter<Schema.SchemaClass<bigint, bigint, never>>>
schema
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
(-3n))
// 输出:-1n
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 decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
(0n))
// 输出:0n
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 decode: (u: unknown, overrideOptions?: ParseOptions) => bigint
decode
(3n))
// 输出:1n

将字符串转换为有效的Date,确保拒绝无效日期,如new Date("Invalid Date")

示例(解析和验证日期)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => Date
decode
=
import Schema
Schema
.
decodeUnknownSync<Date, string>(schema: Schema.Schema<Date, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => Date
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class Date
export Date

This schema converts a string into a Date object using the new Date constructor. It ensures that only valid date strings are accepted, rejecting any strings that would result in an invalid date, such as new Date("Invalid Date").

@since3.10.0

Date
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => Date
decode
("1970-01-01T00:00:00.000Z"))
// 输出:1970-01-01T00:00:00.000Z
const decode: (u: unknown, overrideOptions?: ParseOptions) => Date
decode
("a")
/*
抛出:
ParseError: Date
└─ Predicate refinement failure
└─ Expected Date, actual Invalid Date
*/
const
const validate: (u: unknown, overrideOptions?: ParseOptions) => Date
validate
=
import Schema
Schema
.
validateSync<Date, string, never>(schema: Schema.Schema<Date, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => Date
export validateSync

@throwsParseError

@since3.10.0

validateSync
(
import Schema
Schema
.
class Date
export Date

This schema converts a string into a Date object using the new Date constructor. It ensures that only valid date strings are accepted, rejecting any strings that would result in an invalid date, such as new Date("Invalid Date").

@since3.10.0

Date
)
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 validate: (u: unknown, overrideOptions?: ParseOptions) => Date
validate
(new
var Date: DateConstructor
new (value: number | string | Date) => Date (+3 overloads)
Date
(0)))
// 输出:1970-01-01T00:00:00.000Z
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 validate: (u: unknown, overrideOptions?: ParseOptions) => Date
validate
(new
var Date: DateConstructor
new (value: number | string | Date) => Date (+3 overloads)
Date
("Invalid Date")))
/*
抛出:
ParseError: Date
└─ Predicate refinement failure
└─ Expected Date, actual Invalid Date
*/

将字符串转换为BigDecimal

示例(从字符串解析BigDecimal)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => BigDecimal
decode
=
import Schema
Schema
.
decodeUnknownSync<BigDecimal, string>(schema: Schema.Schema<BigDecimal, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => BigDecimal
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class BigDecimal

@since3.10.0

BigDecimal
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => BigDecimal
decode
(".124"))
// 输出:{ _id: 'BigDecimal', value: '124', scale: 3 }

将数字转换为BigDecimal

示例(从数字解析BigDecimal)

import {
import Schema
Schema
} from "effect"
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => BigDecimal
decode
=
import Schema
Schema
.
decodeUnknownSync<BigDecimal, number>(schema: Schema.Schema<BigDecimal, number, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => BigDecimal
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
import Schema
Schema
.
class BigDecimalFromNumber

A schema that transforms a number into a BigDecimal. When encoding, this Schema will produce incorrect results if the BigDecimal exceeds the 64-bit range of a number.

@since3.10.0

BigDecimalFromNumber
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => BigDecimal
decode
(0.111))
// 输出:{ _id: 'BigDecimal', value: '111', scale: 3 }

BigDecimal限制在指定范围内。

示例(限制BigDecimal)

import {
import Schema
Schema
} from "effect"
import {
import BigDecimal
BigDecimal
} from "effect"
const
const schema: Schema.transform<typeof Schema.BigDecimal, Schema.filter<Schema.SchemaClass<BigDecimal.BigDecimal, BigDecimal.BigDecimal, never>>>
schema
=
import Schema
Schema
.
class BigDecimal

@since3.10.0

BigDecimal
.
Pipeable.pipe<typeof Schema.BigDecimal, Schema.transform<typeof Schema.BigDecimal, Schema.filter<Schema.SchemaClass<BigDecimal.BigDecimal, BigDecimal.BigDecimal, never>>>>(this: typeof Schema.BigDecimal, ab: (_: typeof Schema.BigDecimal) => Schema.transform<typeof Schema.BigDecimal, Schema.filter<Schema.SchemaClass<BigDecimal.BigDecimal, BigDecimal.BigDecimal, never>>>): Schema.transform<typeof Schema.BigDecimal, Schema.filter<Schema.SchemaClass<BigDecimal.BigDecimal, BigDecimal.BigDecimal, never>>> (+21 overloads)
pipe
(
import Schema
Schema
.
const clampBigDecimal: (minimum: BigDecimal.BigDecimal, maximum: BigDecimal.BigDecimal) => <S extends Schema.Schema<in out A, in out I = A, out R = never>.Any, A extends BigDecimal.BigDecimal>(self: S & Schema.Schema<A, Schema.Schema.Encoded<S>, Schema.Schema.Context<S>>) => Schema.transform<S, Schema.filter<Schema.SchemaClass<A>>>

Clamps a BigDecimal between a minimum and a maximum value.

@since3.10.0

clampBigDecimal
(
import BigDecimal
BigDecimal
.
const fromNumber: (n: number) => BigDecimal.BigDecimal

Creates a BigDecimal from a number value.

It is not recommended to convert a floating point number to a decimal directly, as the floating point representation may be unexpected.

Throws a RangeError if the number is not finite (NaN, +Infinity or -Infinity).

@since2.0.0

@deprecatedUse unsafeFromNumber instead.

fromNumber
(-1),
import BigDecimal
BigDecimal
.
const fromNumber: (n: number) => BigDecimal.BigDecimal

Creates a BigDecimal from a number value.

It is not recommended to convert a floating point number to a decimal directly, as the floating point representation may be unexpected.

Throws a RangeError if the number is not finite (NaN, +Infinity or -Infinity).

@since2.0.0

@deprecatedUse unsafeFromNumber instead.

fromNumber
(1)
)
)
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => BigDecimal.BigDecimal
decode
=
import Schema
Schema
.
decodeUnknownSync<BigDecimal.BigDecimal, string>(schema: Schema.Schema<BigDecimal.BigDecimal, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => BigDecimal.BigDecimal
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.transform<typeof Schema.BigDecimal, Schema.filter<Schema.SchemaClass<BigDecimal.BigDecimal, BigDecimal.BigDecimal, never>>>
schema
)
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 decode: (u: unknown, overrideOptions?: ParseOptions) => BigDecimal.BigDecimal
decode
("-2"))
// 输出:{ _id: 'BigDecimal', value: '-1', scale: 0 }
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 decode: (u: unknown, overrideOptions?: ParseOptions) => BigDecimal.BigDecimal
decode
("0"))
// 输出:{ _id: 'BigDecimal', value: '0', scale: 0 }
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 decode: (u: unknown, overrideOptions?: ParseOptions) => BigDecimal.BigDecimal
decode
("3"))
// 输出:{ _id: 'BigDecimal', value: '1', scale: 0 }