Skip to content

错误消息

默认情况下,当发生解析错误时,系统会根据模式的结构和错误的性质自动生成信息性消息(有关更多信息,请参阅 TreeFormatter)。 例如,如果缺少必需属性或数据类型不匹配,错误消息将清楚地说明期望与实际输入的对比。

示例(类型不匹配)

import {
import Schema
Schema
} from "effect"
const
const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person
=
import Schema
Schema
.
function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)

@since3.10.0

Struct
({
name: typeof Schema.String
name
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
age: typeof Schema.Number
age
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
import Schema
Schema
.
decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person
)(null)
// 输出:ParseError: Expected { readonly name: string; readonly age: number }, actual null

示例(缺少属性)

import {
import Schema
Schema
} from "effect"
const
const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person
=
import Schema
Schema
.
function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)

@since3.10.0

Struct
({
name: typeof Schema.String
name
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
age: typeof Schema.Number
age
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
import Schema
Schema
.
decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person
)({}, {
ParseOptions.errors?: "first" | "all" | undefined

The errors option allows you to receive all parsing errors when attempting to parse a value using a schema. By default only the first error is returned, but by setting the errors option to "all", you can receive all errors that occurred during the parsing process. This can be useful for debugging or for providing more comprehensive error messages to the user.

default: "first"

@since3.10.0

errors
: "all" })
/*
抛出:
ParseError: { readonly name: string; readonly age: number }
├─ ["name"]
│ └─ is missing
└─ ["age"]
└─ is missing
*/

示例(错误的属性类型)

import {
import Schema
Schema
} from "effect"
const
const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person
=
import Schema
Schema
.
function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)

@since3.10.0

Struct
({
name: typeof Schema.String
name
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
age: typeof Schema.Number
age
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
import Schema
Schema
.
decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person
)(
{
name: null
name
: null,
age: string
age
: "age" },
{
ParseOptions.errors?: "first" | "all" | undefined

The errors option allows you to receive all parsing errors when attempting to parse a value using a schema. By default only the first error is returned, but by setting the errors option to "all", you can receive all errors that occurred during the parsing process. This can be useful for debugging or for providing more comprehensive error messages to the user.

default: "first"

@since3.10.0

errors
: "all" }
)
/*
抛出:
ParseError: { readonly name: string; readonly age: number }
├─ ["name"]
│ └─ Expected string, actual null
└─ ["age"]
└─ Expected number, actual "age"
*/

在模式具有多个字段或嵌套结构的场景中,默认错误消息可能变得过于复杂和冗长。 为了解决这个问题,您可以通过使用 identifiertitledescription 等注解来增强这些消息的清晰度和简洁性。

示例(使用标识符提高清晰度)

import {
import Schema
Schema
} from "effect"
const
const Name: Schema.SchemaClass<string, string, never>
Name
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.SchemaClass<string, string, never>

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

annotations
({
Annotations.Schema<string, readonly []>.identifier?: string
identifier
: "Name" })
const
const Age: Schema.SchemaClass<number, number, never>
Age
=
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
.
Annotable<SchemaClass<number, number, never>, number, number, never>.annotations(annotations: Schema.Annotations.GenericSchema<number>): Schema.SchemaClass<number, number, never>

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

annotations
({
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.identifier?: string
identifier
: "Age" })
const
const Person: Schema.Struct<{
name: Schema.SchemaClass<string, string, never>;
age: Schema.SchemaClass<number, number, never>;
}>
Person
=
import Schema
Schema
.
function Struct<{
name: Schema.SchemaClass<string, string, never>;
age: Schema.SchemaClass<number, number, never>;
}>(fields: {
name: Schema.SchemaClass<string, string, never>;
age: Schema.SchemaClass<number, number, never>;
}): Schema.Struct<{
name: Schema.SchemaClass<string, string, never>;
age: Schema.SchemaClass<number, number, never>;
}> (+1 overload)

@since3.10.0

Struct
({
name: Schema.SchemaClass<string, string, never>
name
:
const Name: Schema.SchemaClass<string, string, never>
Name
,
age: Schema.SchemaClass<number, number, never>
age
:
const Age: Schema.SchemaClass<number, number, never>
Age
}).
Struct<{ name: SchemaClass<string, string, never>; age: SchemaClass<number, number, never>; }>.annotations(annotations: Schema.Annotations.Schema<{
readonly name: string;
readonly age: number;
}, readonly []>): Schema.Struct<{
name: Schema.SchemaClass<string, string, never>;
age: Schema.SchemaClass<number, number, never>;
}>

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

annotations
({
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.identifier?: string
identifier
: "Person" })
import Schema
Schema
.
decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: Schema.SchemaClass<string, string, never>;
age: Schema.SchemaClass<number, number, never>;
}>
Person
)(null)
/*
抛出:
ParseError: Expected Person, actual null
*/
import Schema
Schema
.
decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: Schema.SchemaClass<string, string, never>;
age: Schema.SchemaClass<number, number, never>;
}>
Person
)({}, {
ParseOptions.errors?: "first" | "all" | undefined

The errors option allows you to receive all parsing errors when attempting to parse a value using a schema. By default only the first error is returned, but by setting the errors option to "all", you can receive all errors that occurred during the parsing process. This can be useful for debugging or for providing more comprehensive error messages to the user.

default: "first"

@since3.10.0

errors
: "all" })
/*
抛出:
ParseError: Person
├─ ["name"]
│ └─ is missing
└─ ["age"]
└─ is missing
*/
import Schema
Schema
.
decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: Schema.SchemaClass<string, string, never>;
age: Schema.SchemaClass<number, number, never>;
}>
Person
)(
{
name: null
name
: null,
age: null
age
: null },
{
ParseOptions.errors?: "first" | "all" | undefined

The errors option allows you to receive all parsing errors when attempting to parse a value using a schema. By default only the first error is returned, but by setting the errors option to "all", you can receive all errors that occurred during the parsing process. This can be useful for debugging or for providing more comprehensive error messages to the user.

default: "first"

@since3.10.0

errors
: "all" }
)
/*
抛出:
ParseError: Person
├─ ["name"]
│ └─ Expected Name, actual null
└─ ["age"]
└─ Expected Age, actual null
*/

当精炼失败时,默认错误消息指示失败是发生在”from”部分还是在定义精炼的谓词内:

示例(精炼错误)

import {
import Schema
Schema
} from "effect"
const
const Name: Schema.refine<string, typeof Schema.String>
Name
=
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
.
Annotable<refine<string, typeof String$>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.refine<string, typeof Schema.String>

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

annotations
({
Annotations.Schema<string, readonly []>.identifier?: string
identifier
: "Name" })
const
const Age: Schema.filter<typeof Schema.Positive>
Age
=
import Schema
Schema
.
class Positive

@since3.10.0

Positive
.
Pipeable.pipe<typeof Schema.Positive, Schema.filter<typeof Schema.Positive>>(this: typeof Schema.Positive, ab: (_: typeof Schema.Positive) => Schema.filter<typeof Schema.Positive>): Schema.filter<typeof Schema.Positive> (+21 overloads)
pipe
(
import Schema
Schema
.
const int: <typeof Schema.Positive>(annotations?: Schema.Annotations.Filter<number, number> | undefined) => <A>(self: typeof Schema.Positive & Schema.Schema<A, number, never>) => Schema.filter<typeof Schema.Positive>

Ensures that the provided value is an integer number (excluding NaN, +Infinity, and -Infinity).

@since3.10.0

int
({
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.identifier?: string
identifier
: "Age" }))
const
const Person: Schema.Struct<{
name: Schema.refine<string, typeof Schema.String>;
age: Schema.filter<typeof Schema.Positive>;
}>
Person
=
import Schema
Schema
.
function Struct<{
name: Schema.refine<string, typeof Schema.String>;
age: Schema.filter<typeof Schema.Positive>;
}>(fields: {
name: Schema.refine<string, typeof Schema.String>;
age: Schema.filter<typeof Schema.Positive>;
}): Schema.Struct<{
name: Schema.refine<string, typeof Schema.String>;
age: Schema.filter<typeof Schema.Positive>;
}> (+1 overload)

@since3.10.0

Struct
({
name: Schema.refine<string, typeof Schema.String>
name
:
const Name: Schema.refine<string, typeof Schema.String>
Name
,
age: Schema.filter<typeof Schema.Positive>
age
:
const Age: Schema.filter<typeof Schema.Positive>
Age
}).
Struct<{ name: refine<string, typeof String$>; age: filter<typeof Positive>; }>.annotations(annotations: Schema.Annotations.Schema<{
readonly name: string;
readonly age: number;
}, readonly []>): Schema.Struct<{
name: Schema.refine<string, typeof Schema.String>;
age: Schema.filter<typeof Schema.Positive>;
}>

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

annotations
({
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.identifier?: string
identifier
: "Person" })
// From侧失败
import Schema
Schema
.
decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: Schema.refine<string, typeof Schema.String>;
age: Schema.filter<typeof Schema.Positive>;
}>
Person
)({
name: null
name
: null,
age: number
age
: 18 })
/*
throws:
ParseError: Person
└─ ["name"]
└─ Name
└─ From side refinement failure
└─ Expected string, actual null
*/
// 谓词精炼失败
import Schema
Schema
.
decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: Schema.refine<string, typeof Schema.String>;
age: Schema.filter<typeof Schema.Positive>;
}>
Person
)({
name: string
name
: "",
age: number
age
: 18 })
/*
throws:
ParseError: Person
└─ ["name"]
└─ Name
└─ Predicate refinement failure
└─ Expected a non empty string, actual ""
*/

在第一个示例中,错误消息指示name属性中的”from side”精炼失败,指定期望字符串但收到了null。 在第二个示例中,报告了”predicate”精炼失败,指示name期望非空字符串但提供了空字符串。

不同类型或格式之间的转换偶尔会导致错误。 系统提供结构化的错误消息来指定错误发生的位置:

  • 编码侧失败: 此侧的错误通常表示转换的输入与预期的初始类型或格式不匹配。例如,期望string时收到null
  • 转换过程失败: 当转换逻辑本身失败时会出现此类错误,例如当输入不满足转换函数中指定的条件时。
  • 类型侧失败: 当转换的输出不满足解码侧的模式要求时发生。如果转换后的值未通过后续验证或条件,就会发生这种情况。

示例(转换错误)

import {
import ParseResult
ParseResult
,
import Schema
Schema
} from "effect"
const
const schema: Schema.transformOrFail<typeof Schema.String, Schema.filter<typeof Schema.String>, never>
schema
=
import Schema
Schema
.
const transformOrFail: <Schema.filter<typeof Schema.String>, typeof Schema.String, never, never>(from: typeof Schema.String, to: Schema.filter<typeof Schema.String>, options: {
readonly decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect<string, ParseResult.ParseIssue, never>;
readonly encode: (toI: string, options: ParseOptions, ast: Transformation, toA: string) => 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
,
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.filter<typeof Schema.String>>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.filter<typeof Schema.String>): Schema.filter<typeof Schema.String> (+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
(2)),
{
strict?: true
strict
: true,
decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect<string, ParseResult.ParseIssue, never>
decode
: (
s: string
s
,
_: ParseOptions
_
,
ast: Transformation
ast
) =>
s: string
s
.
String.length: number

Returns the length of a String object.

length
> 0
?
import ParseResult
ParseResult
.
const succeed: <string>(a: string) => Either<string, ParseResult.ParseIssue>

@since3.10.0

succeed
(
s: string
s
)
:
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
,
s: string
s
)),
encode: (toI: string, options: ParseOptions, ast: Transformation, toA: string) => Effect<string, ParseResult.ParseIssue, never>
encode
:
import ParseResult
ParseResult
.
const succeed: <A>(a: A) => Either<A, ParseResult.ParseIssue>

@since3.10.0

succeed
}
)
// 编码侧失败
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
(
const schema: Schema.transformOrFail<typeof Schema.String, Schema.filter<typeof Schema.String>, never>
schema
)(null)
/*
throws:
ParseError: (string <-> minLength(2))
└─ Encoded side transformation failure
└─ Expected string, actual null
*/
// 转换失败
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
(
const schema: Schema.transformOrFail<typeof Schema.String, Schema.filter<typeof Schema.String>, never>
schema
)("")
/*
throws:
ParseError: (string <-> minLength(2))
└─ Transformation process failure
└─ Expected (string <-> minLength(2)), actual ""
*/
// 类型侧失败
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
(
const schema: Schema.transformOrFail<typeof Schema.String, Schema.filter<typeof Schema.String>, never>
schema
)("a")
/*
throws:
ParseError: (string <-> minLength(2))
└─ Type side transformation failure
└─ minLength(2)
└─ Predicate refinement failure
└─ Expected a string at least 2 character(s) long, actual "a"
*/

您可以使用message注解为模式的不同部分定义专门定制的自定义错误消息。 这允许开发人员提供更具上下文特定性的反馈,可以改善调试和验证过程。

以下是MessageAnnotation类型的概述,您可以使用它来制作这些消息:

type MessageAnnotation = (issue: ParseIssue) =>
| string
| Effect<string>
| {
readonly message: string | Effect<string>
readonly override: boolean
}
返回类型描述
string提供直接描述错误的静态消息。
Effect<string>利用可以合并同步过程结果或依赖可选依赖项的动态消息。
Object (with message and override)允许您定义特定的错误消息以及布尔标志(override)。此标志确定自定义消息是否应取代任何默认或嵌套的自定义消息,为显示给用户的错误输出提供精确控制。

示例(为字符串模式添加自定义错误消息)

import {
import Schema
Schema
} from "effect"
// 定义没有自定义消息的字符串模式
const
const MyString: typeof Schema.String
MyString
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
// 尝试解码`null`,导致默认错误消息
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
(
const MyString: typeof Schema.String
MyString
)(null)
/*
throws:
ParseError: Expected string, actual null
*/
// 定义带有自定义错误消息的字符串模式
const
const MyStringWithMessage: Schema.SchemaClass<string, string, never>
MyStringWithMessage
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.SchemaClass<string, string, never>

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

annotations
({
Annotations.Schema<string, readonly []>.message?: MessageAnnotation
message
: () => "not a string"
})
// 使用自定义模式解码,显示新的错误消息
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
(
const MyStringWithMessage: Schema.SchemaClass<string, string, never>
MyStringWithMessage
)(null)
/*
throws:
ParseError: not a string
*/

示例(带有覆盖选项的联合模式的自定义错误消息)

import {
import Schema
Schema
} from "effect"
// 定义没有自定义消息的联合模式
const
const MyUnion: Schema.Union<[typeof Schema.String, typeof Schema.Number]>
MyUnion
=
import Schema
Schema
.
function Union<[typeof Schema.String, typeof Schema.Number]>(members_0: typeof Schema.String, members_1: typeof Schema.Number): Schema.Union<[typeof Schema.String, typeof Schema.Number]> (+3 overloads)

@since3.10.0

Union
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
)
// 解码`null`,导致默认联合错误消息
import Schema
Schema
.
decodeUnknownSync<string | number, string | number>(schema: Schema.Schema<string | number, string | number, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string | number
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const MyUnion: Schema.Union<[typeof Schema.String, typeof Schema.Number]>
MyUnion
)(null)
/*
throws:
ParseError: string | number
├─ Expected string, actual null
└─ Expected number, actual null
*/
// 定义带有自定义消息和覆盖标志的联合模式
const
const MyUnionWithMessage: Schema.Union<[typeof Schema.String, typeof Schema.Number]>
MyUnionWithMessage
=
import Schema
Schema
.
function Union<[typeof Schema.String, typeof Schema.Number]>(members_0: typeof Schema.String, members_1: typeof Schema.Number): Schema.Union<[typeof Schema.String, typeof Schema.Number]> (+3 overloads)

@since3.10.0

Union
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
).
Annotable<Union<[typeof String$, typeof Number$]>, string | number, string | number, never>.annotations(annotations: Schema.Annotations.GenericSchema<string | number>): Schema.Union<[typeof Schema.String, typeof Schema.Number]>

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

annotations
({
Annotations.Schema<string | number, readonly []>.message?: MessageAnnotation
message
: () => ({
message: string | Effect<string, never, never>
message
: "Please provide a string or a number",
// 确保此消息替换所有嵌套消息
override: boolean
override
: true
})
})
// 使用自定义模式解码,显示新的错误消息
import Schema
Schema
.
decodeUnknownSync<string | number, string | number>(schema: Schema.Schema<string | number, string | number, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string | number
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const MyUnionWithMessage: Schema.Union<[typeof Schema.String, typeof Schema.Number]>
MyUnionWithMessage
)(null)
/*
throws:
ParseError: Please provide a string or a number
*/

确定消息遵循的一般逻辑如下:

  1. 如果没有设置自定义消息,则使用与操作(即解码或编码)失败的最内层模式相关的默认消息。

  2. 如果设置了自定义消息,则使用对应于第一个失败模式的消息,从最内层模式开始到最外层模式。但是,如果失败的模式没有自定义消息,则使用默认消息

  3. 作为可选功能,您可以通过将overwrite标志设置为true来覆盖准则2。这允许自定义消息优先于来自内部模式的所有其他自定义消息。这是为了解决用户想要定义单个累积自定义消息来描述有效值必须具有的属性并且不想看到默认消息的场景。

让我们看一些实际示例。

示例(标量模式的简单自定义消息)

import {
import Schema
Schema
} from "effect"
const
const MyString: Schema.SchemaClass<string, string, never>
MyString
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.SchemaClass<string, string, never>

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

annotations
({
Annotations.Schema<string, readonly []>.message?: MessageAnnotation
message
: () => "my custom message"
})
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
(
const MyString: Schema.SchemaClass<string, string, never>
MyString
)
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(null)
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // "my custom message"
}

此示例演示在精炼链中的最后一个精炼上设置自定义消息。如您所见,只有当与maxLength相关的精炼失败时才使用自定义消息;否则,使用默认消息。

示例(链中最后一个精炼的自定义消息)

import {
import Schema
Schema
} from "effect"
const
const MyString: Schema.refine<string, Schema.filter<typeof Schema.String>>
MyString
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.filter<typeof Schema.String>, Schema.filter<Schema.filter<typeof Schema.String>>>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.filter<typeof Schema.String>, bc: (_: Schema.filter<typeof Schema.String>) => Schema.filter<Schema.filter<typeof Schema.String>>): Schema.filter<Schema.filter<typeof Schema.String>> (+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
(1),
import Schema
Schema
.
const maxLength: <Schema.filter<typeof Schema.String>>(maxLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: Schema.filter<typeof Schema.String> & Schema.Schema<A, string, never>) => Schema.filter<Schema.filter<typeof Schema.String>>

@since3.10.0

maxLength
(2)
).
Annotable<refine<string, filter<typeof String$>>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.refine<string, Schema.filter<typeof Schema.String>>

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

annotations
({
// 此消息仅在最后一个过滤器(`maxLength`)失败时显示
Annotations.Schema<string, readonly []>.message?: MessageAnnotation
message
: () => "my custom message"
})
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
(
const MyString: Schema.refine<string, Schema.filter<typeof Schema.String>>
MyString
)
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(null)
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
)
/*
minLength(1) & maxLength(2)
└─ From side refinement failure
└─ minLength(1)
└─ From side refinement failure
└─ Expected string, actual null
*/
}
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("")
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
)
/*
minLength(1) & maxLength(2)
└─ From side refinement failure
└─ minLength(1)
└─ Predicate refinement failure
└─ Expected a string at least 1 character(s) long, actual ""
*/
}
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("abc")
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
)
// "my custom message"
}

当设置多个自定义消息时,使用对应于第一个失败谓词的消息,从最内层精炼开始到最外层:

示例(多个精炼的自定义消息)

import {
import Schema
Schema
} from "effect"
const
const MyString: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>
MyString
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
// 此消息仅在传入非字符串输入时显示
.
Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.SchemaClass<string, string, never>

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

annotations
({
Annotations.Schema<string, readonly []>.message?: MessageAnnotation
message
: () => "String custom message" })
.
Pipeable.pipe<Schema.SchemaClass<string, string, never>, Schema.filter<Schema.SchemaClass<string, string, never>>, Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>>(this: Schema.SchemaClass<...>, ab: (_: Schema.SchemaClass<string, string, never>) => Schema.filter<Schema.SchemaClass<string, string, never>>, bc: (_: Schema.filter<Schema.SchemaClass<string, string, never>>) => Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>): Schema.filter<...> (+21 overloads)
pipe
(
// 此消息仅在过滤器`minLength`失败时显示
import Schema
Schema
.
const minLength: <Schema.SchemaClass<string, string, never>>(minLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: Schema.SchemaClass<string, string, never> & Schema.Schema<A, string, never>) => Schema.filter<Schema.SchemaClass<string, string, never>>

@since3.10.0

minLength
(1, {
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "minLength custom message" }),
// 此消息仅在过滤器`maxLength`失败时显示
import Schema
Schema
.
const maxLength: <Schema.filter<Schema.SchemaClass<string, string, never>>>(maxLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: Schema.filter<Schema.SchemaClass<string, string, never>> & Schema.Schema<A, string, never>) => Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>

@since3.10.0

maxLength
(2, {
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "maxLength custom message" })
)
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
(
const MyString: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>
MyString
)
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(null)
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // String custom message
}
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("")
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // minLength custom message
}
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("abc")
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // maxLength custom message
}

您可以通过将override标志设置为true来更改默认行为。当您想要创建一个描述有效值所需属性的单一综合自定义消息而不显示默认消息时,这很有用。

示例(覆盖默认消息)

import {
import Schema
Schema
} from "effect"
const
const MyString: Schema.refine<string, Schema.filter<typeof Schema.String>>
MyString
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.filter<typeof Schema.String>, Schema.filter<Schema.filter<typeof Schema.String>>>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.filter<typeof Schema.String>, bc: (_: Schema.filter<typeof Schema.String>) => Schema.filter<Schema.filter<typeof Schema.String>>): Schema.filter<Schema.filter<typeof Schema.String>> (+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
(1),
import Schema
Schema
.
const maxLength: <Schema.filter<typeof Schema.String>>(maxLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: Schema.filter<typeof Schema.String> & Schema.Schema<A, string, never>) => Schema.filter<Schema.filter<typeof Schema.String>>

@since3.10.0

maxLength
(2)
).
Annotable<refine<string, filter<typeof String$>>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.refine<string, Schema.filter<typeof Schema.String>>

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

annotations
({
// 通过将`override`标志设置为`true`,此消息将始终为任何错误显示
Annotations.Schema<string, readonly []>.message?: MessageAnnotation
message
: () => ({
message: string | Effect<string, never, never>
message
: "my custom message",
override: boolean
override
: true })
})
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
(
const MyString: Schema.refine<string, Schema.filter<typeof Schema.String>>
MyString
)
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
(null)
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // my custom message
}
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("")
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // my custom message
}
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => string
decode
("abc")
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // my custom message
}

在此示例中,IntFromString是一个将字符串转换为整数的转换模式。它根据不同场景应用特定的验证消息。

示例(字符串到整数转换的自定义错误消息)

import {
import ParseResult
ParseResult
,
import Schema
Schema
} from "effect"
const
const IntFromString: Schema.transformOrFail<Schema.SchemaClass<string, string, never>, Schema.refine<number, typeof Schema.Number>, never>
IntFromString
=
import Schema
Schema
.
const transformOrFail: <Schema.refine<number, typeof Schema.Number>, Schema.SchemaClass<string, string, never>, never, never>(from: Schema.SchemaClass<string, string, never>, to: Schema.refine<number, 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<...>;
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
.
Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.SchemaClass<string, string, never>

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

annotations
({
Annotations.Schema<string, readonly []>.message?: MessageAnnotation
message
: () => "please enter a string" }),
// 此消息仅在输入可以转换为数字但不是整数时显示
import Schema
Schema
.
class Int

@since3.10.0

Int
.
Annotable<refine<number, typeof Number$>, number, number, never>.annotations(annotations: Schema.Annotations.GenericSchema<number>): Schema.refine<number, typeof Schema.Number>

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

annotations
({
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "please enter an integer" }),
{
strict?: true
strict
: true,
decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect<number, ParseResult.ParseIssue, never>
decode
: (
s: string
s
,
_: ParseOptions
_
,
ast: Transformation
ast
) => {
const
const n: number
n
=
var Number: NumberConstructor
(value?: any) => number

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

Number
(
s: string
s
)
return
var Number: NumberConstructor

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

Number
.
NumberConstructor.isNaN(number: unknown): boolean

Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). Unlike the global isNaN(), Number.isNaN() doesn't forcefully convert the parameter to a number. Only values of the type number, that are also NaN, result in true.

@paramnumber A numeric value.

isNaN
(
const n: number
n
)
?
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
,
s: string
s
))
:
import ParseResult
ParseResult
.
const succeed: <number>(a: number) => Either<number, ParseResult.ParseIssue>

@since3.10.0

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

@since3.10.0

succeed
(
var String: StringConstructor
(value?: any) => string

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

String
(
n: number
n
))
}
)
// 此消息仅在输入无法转换为数字时显示
.
Annotable<transformOrFail<SchemaClass<string, string, never>, refine<number, typeof Number$>, never>, number, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<number>): Schema.transformOrFail<Schema.SchemaClass<string, string, never>, Schema.refine<number, typeof Schema.Number>, never>

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

annotations
({
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "please enter a parseable string" })
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 IntFromString: Schema.transformOrFail<Schema.SchemaClass<string, string, never>, Schema.refine<number, typeof Schema.Number>, never>
IntFromString
)
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
(null)
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // please enter a string
}
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("1.2")
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // please enter an integer
}
try {
const decode: (u: unknown, overrideOptions?: ParseOptions) => number
decode
("not a number")
} catch (
var e: any
e
: any) {
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
(
var e: any
e
.
any
message
) // please enter a parseable string
}

stringnumber等简单标量值不同,自定义消息系统在处理复杂模式时变得特别有用。例如,考虑一个包含嵌套结构的模式,如包含其他结构数组的结构。让我们探索一个示例,演示默认消息在处理此类嵌套结构中的解码错误时的优势:

示例(嵌套模式中的自定义错误消息)

import {
import Schema
Schema
,
function pipe<A>(a: A): A (+19 overloads)

Pipes the value of an expression into a pipeline of functions.

Details

The pipe function is a utility that allows us to compose functions in a readable and sequential manner. It takes the output of one function and passes it as the input to the next function in the pipeline. This enables us to build complex transformations by chaining multiple functions together.

import { pipe } from "effect"
const result = pipe(input, func1, func2, ..., funcN)

In this syntax, input is the initial value, and func1, func2, ..., funcN are the functions to be applied in sequence. The result of each function becomes the input for the next function, and the final result is returned.

Here's an illustration of how pipe works:

┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌────────┐
│ input │───►│ func1 │───►│ func2 │───►│ ... │───►│ funcN │───►│ result │
└───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └────────┘

It's important to note that functions passed to pipe must have a single argument because they are only called with a single argument.

When to Use

This is useful in combination with data-last functions as a simulation of methods:

as.map(f).filter(g)

becomes:

import { pipe, Array } from "effect"
pipe(as, Array.map(f), Array.filter(g))

Example (Chaining Arithmetic Operations)

import { pipe } from "effect"
// Define simple arithmetic operations
const increment = (x: number) => x + 1
const double = (x: number) => x * 2
const subtractTen = (x: number) => x - 10
// Sequentially apply these operations using `pipe`
const result = pipe(5, increment, double, subtractTen)
console.log(result)
// Output: 2

@since2.0.0

pipe
} from "effect"
const
const schema: Schema.Struct<{
outcomes: Schema.filter<Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>>;
}>
schema
=
import Schema
Schema
.
function Struct<{
outcomes: Schema.filter<Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>>;
}>(fields: {
outcomes: Schema.filter<Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>>;
}): Schema.Struct<{
outcomes: Schema.filter<Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>>;
}> (+1 overload)

@since3.10.0

Struct
({
outcomes: Schema.filter<Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>>
outcomes
:
pipe<Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>, Schema.filter<Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>>>(a: Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>, ab: (a: Schema.Array$<...>) => Schema.filter<...>): Schema.filter<...> (+19 overloads)

Pipes the value of an expression into a pipeline of functions.

Details

The pipe function is a utility that allows us to compose functions in a readable and sequential manner. It takes the output of one function and passes it as the input to the next function in the pipeline. This enables us to build complex transformations by chaining multiple functions together.

import { pipe } from "effect"
const result = pipe(input, func1, func2, ..., funcN)

In this syntax, input is the initial value, and func1, func2, ..., funcN are the functions to be applied in sequence. The result of each function becomes the input for the next function, and the final result is returned.

Here's an illustration of how pipe works:

┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌────────┐
│ input │───►│ func1 │───►│ func2 │───►│ ... │───►│ funcN │───►│ result │
└───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └────────┘

It's important to note that functions passed to pipe must have a single argument because they are only called with a single argument.

When to Use

This is useful in combination with data-last functions as a simulation of methods:

as.map(f).filter(g)

becomes:

import { pipe, Array } from "effect"
pipe(as, Array.map(f), Array.filter(g))

Example (Chaining Arithmetic Operations)

import { pipe } from "effect"
// Define simple arithmetic operations
const increment = (x: number) => x + 1
const double = (x: number) => x * 2
const subtractTen = (x: number) => x - 10
// Sequentially apply these operations using `pipe`
const result = pipe(5, increment, double, subtractTen)
console.log(result)
// Output: 2

@since2.0.0

pipe
(
import Schema
Schema
.
Array<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>(value: Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>): Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>
export Array

@since3.10.0

Array
(
import Schema
Schema
.
function Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>(fields: {
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}): Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}> (+1 overload)

@since3.10.0

Struct
({
id: typeof Schema.String
id
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>
text
:
pipe<Schema.SchemaClass<string, string, never>, Schema.filter<Schema.SchemaClass<string, string, never>>, Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>>(a: Schema.SchemaClass<string, string, never>, ab: (a: Schema.SchemaClass<string, string, never>) => Schema.filter<Schema.SchemaClass<string, string, never>>, bc: (b: Schema.filter<Schema.SchemaClass<string, string, never>>) => Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>): Schema.filter<...> (+19 overloads)

Pipes the value of an expression into a pipeline of functions.

Details

The pipe function is a utility that allows us to compose functions in a readable and sequential manner. It takes the output of one function and passes it as the input to the next function in the pipeline. This enables us to build complex transformations by chaining multiple functions together.

import { pipe } from "effect"
const result = pipe(input, func1, func2, ..., funcN)

In this syntax, input is the initial value, and func1, func2, ..., funcN are the functions to be applied in sequence. The result of each function becomes the input for the next function, and the final result is returned.

Here's an illustration of how pipe works:

┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌────────┐
│ input │───►│ func1 │───►│ func2 │───►│ ... │───►│ funcN │───►│ result │
└───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └────────┘

It's important to note that functions passed to pipe must have a single argument because they are only called with a single argument.

When to Use

This is useful in combination with data-last functions as a simulation of methods:

as.map(f).filter(g)

becomes:

import { pipe, Array } from "effect"
pipe(as, Array.map(f), Array.filter(g))

Example (Chaining Arithmetic Operations)

import { pipe } from "effect"
// Define simple arithmetic operations
const increment = (x: number) => x + 1
const double = (x: number) => x * 2
const subtractTen = (x: number) => x - 10
// Sequentially apply these operations using `pipe`
const result = pipe(5, increment, double, subtractTen)
console.log(result)
// Output: 2

@since2.0.0

pipe
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.SchemaClass<string, string, never>

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

annotations
({
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "error_invalid_outcome_type"
}),
import Schema
Schema
.
const minLength: <Schema.SchemaClass<string, string, never>>(minLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: Schema.SchemaClass<string, string, never> & Schema.Schema<A, string, never>) => Schema.filter<Schema.SchemaClass<string, string, never>>

@since3.10.0

minLength
(1, {
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "error_required_field" }),
import Schema
Schema
.
const maxLength: <Schema.filter<Schema.SchemaClass<string, string, never>>>(maxLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: Schema.filter<Schema.SchemaClass<string, string, never>> & Schema.Schema<A, string, never>) => Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>

@since3.10.0

maxLength
(50, {
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "error_max_length_field"
})
)
})
),
import Schema
Schema
.
const minItems: <Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>>(n: number, annotations?: Schema.Annotations.Filter<readonly {
readonly id: string;
readonly text: string;
}[], readonly {
readonly id: string;
readonly text: string;
}[]> | undefined) => <A>(self: Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>> & Schema.Schema<...>) => Schema.filter<...>

@since3.10.0

minItems
(1, {
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "error_min_length_field" })
)
})
import Schema
Schema
.
decodeUnknownSync<{
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}, {
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}>(schema: Schema.Schema<{
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}, {
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Struct<{
outcomes: Schema.filter<Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>>;
}>
schema
, {
ParseOptions.errors?: "first" | "all" | undefined

The errors option allows you to receive all parsing errors when attempting to parse a value using a schema. By default only the first error is returned, but by setting the errors option to "all", you can receive all errors that occurred during the parsing process. This can be useful for debugging or for providing more comprehensive error messages to the user.

default: "first"

@since3.10.0

errors
: "all" })({
outcomes: never[]
outcomes
: []
})
/*
throws
ParseError: { readonly outcomes: minItems(1) }
└─ ["outcomes"]
└─ error_min_length_field
*/
import Schema
Schema
.
decodeUnknownSync<{
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}, {
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}>(schema: Schema.Schema<{
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}, {
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly outcomes: readonly {
readonly id: string;
readonly text: string;
}[];
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Struct<{
outcomes: Schema.filter<Schema.Array$<Schema.Struct<{
id: typeof Schema.String;
text: Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>;
}>>>;
}>
schema
, {
ParseOptions.errors?: "first" | "all" | undefined

The errors option allows you to receive all parsing errors when attempting to parse a value using a schema. By default only the first error is returned, but by setting the errors option to "all", you can receive all errors that occurred during the parsing process. This can be useful for debugging or for providing more comprehensive error messages to the user.

default: "first"

@since3.10.0

errors
: "all" })({
outcomes: {
id: string;
text: string;
}[]
outcomes
: [
{
id: string
id
: "1",
text: string
text
: "" },
{
id: string
id
: "2",
text: string
text
: "this one is valid" },
{
id: string
id
: "3",
text: string
text
: "1234567890".
String.repeat(count: number): string

Returns a String value that is made from count copies appended together. If count is 0, the empty string is returned.

@paramcount number of copies to append

repeat
(6) }
]
})
/*
throws
ParseError: { readonly outcomes: minItems(1) }
└─ ["outcomes"]
└─ minItems(1)
└─ From side refinement failure
└─ ReadonlyArray<{ readonly id: string; readonly text: minLength(1) & maxLength(50) }>
├─ [0]
│ └─ { readonly id: string; readonly text: minLength(1) & maxLength(50) }
│ └─ ["text"]
│ └─ error_required_field
└─ [2]
└─ { readonly id: string; readonly text: minLength(1) & maxLength(50) }
└─ ["text"]
└─ error_max_length_field
*/

错误消息可以通过返回Effect超越简单字符串,允许它们访问依赖项,如国际化服务。这种方法让消息根据外部上下文或服务动态调整。下面是一个说明如何创建基于效果的消息的示例。

示例(带有国际化服务的基于效果的消息)

import {
import Context

@since2.0.0

@since2.0.0

Context
,
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Either

@since2.0.0

@since2.0.0

Either
,
import Option

@since2.0.0

@since2.0.0

Option
,
import Schema
Schema
,
import ParseResult
ParseResult
} from "effect"
// 为自定义消息定义国际化服务
class
class Messages
Messages
extends
import Context

@since2.0.0

@since2.0.0

Context
.
const Tag: <"Messages">(id: "Messages") => <Self, Shape>() => Context.TagClass<Self, "Messages", 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
("Messages")<
class Messages
Messages
,
{
type NonEmpty: string
NonEmpty
: string
}
>() {}
// 定义一个带有基于效果的消息的模式
// 该消息依赖于Messages服务
const
const Name: Schema.refine<string, typeof Schema.String>
Name
=
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
.
Annotable<refine<string, typeof String$>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.refine<string, typeof Schema.String>

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

annotations
({
Annotations.Schema<string, readonly []>.message?: MessageAnnotation
message
: () =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const gen: <YieldWrap<Effect.Effect<Option.Option<{
NonEmpty: string;
}>, never, never>>, string>(f: (resume: Effect.Adapter) => Generator<YieldWrap<Effect.Effect<Option.Option<{
NonEmpty: string;
}>, never, never>>, string, never>) => Effect.Effect<string, never, never> (+1 overload)

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

When to Use

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

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

Example

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

@since2.0.0

gen
(function* () {
// 尝试检索Messages服务
const
const service: Option.Option<{
NonEmpty: string;
}>
service
= yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const serviceOption: <Messages, {
NonEmpty: string;
}>(tag: Context.Tag<Messages, {
NonEmpty: string;
}>) => Effect.Effect<Option.Option<{
NonEmpty: string;
}>, never, never>

Retrieves an optional service from the context as an Option.

Details

This function retrieves a service from the context and wraps it in an Option. If the service is available, it returns a Some containing the service. If the service is not found, it returns a None. This approach is useful when you want to handle the absence of a service gracefully without causing an error.

When to Use

Use this function when:

  • You need to access a service that may or may not be present in the context.
  • You want to handle the absence of a service using the Option type instead of throwing an error.

@seeserviceOptional for a version that throws an error if the service is missing.

@since2.0.0

serviceOption
(
class Messages
Messages
)
// 如果服务不可用,使用回退消息
return
import Option

@since2.0.0

@since2.0.0

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

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

Details

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

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

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

Example (Pattern Matching with Option)

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

@since2.0.0

match
(
const service: Option.Option<{
NonEmpty: string;
}>
service
, {
onNone: LazyArg<string>
onNone
: () => "Invalid string",
onSome: (a: {
NonEmpty: string;
}) => string
onSome
: (
messages: {
NonEmpty: string;
}
messages
) =>
messages: {
NonEmpty: string;
}
messages
.
type NonEmpty: string
NonEmpty
})
})
})
// 尝试在不提供Messages服务的情况下解码空字符串
import Schema
Schema
.
const decodeUnknownEither: <string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Either.Either<string, ParseResult.ParseError>

@since3.10.0

decodeUnknownEither
(
const Name: Schema.refine<string, typeof Schema.String>
Name
)("").
Pipeable.pipe<Either.Either<string, ParseResult.ParseError>, Either.Either<string, void>>(this: Either.Either<string, ParseResult.ParseError>, ab: (_: Either.Either<string, ParseResult.ParseError>) => Either.Either<string, void>): Either.Either<string, void> (+21 overloads)
pipe
(
import Either

@since2.0.0

@since2.0.0

Either
.
const mapLeft: <ParseResult.ParseError, void>(f: (left: ParseResult.ParseError) => void) => <R>(self: Either.Either<R, ParseResult.ParseError>) => Either.Either<R, void> (+1 overload)

Maps the Left side of an Either value to a new Either value.

@since2.0.0

mapLeft
((
error: ParseResult.ParseError
error
) =>
import ParseResult
ParseResult
.
const TreeFormatter: ParseResult.ParseResultFormatter<string>

@since3.10.0

TreeFormatter
.
ParseResultFormatter<string>.formatError: (error: ParseResult.ParseError) => Effect.Effect<string, never, never>
formatError
(
error: ParseResult.ParseError
error
).
Pipeable.pipe<Effect.Effect<string, never, never>, string, void>(this: Effect.Effect<string, never, never>, ab: (_: Effect.Effect<string, never, never>) => string, bc: (_: string) => void): void (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runSync: <A, E>(effect: Effect.Effect<A, E>) => A

Executes an effect synchronously, running it immediately and returning the result.

Details

This function evaluates the provided effect synchronously, returning its result directly. It is ideal for effects that do not fail or include asynchronous operations. If the effect does fail or involves async tasks, it will throw an error. Execution stops at the point of failure or asynchronous operation, making it unsuitable for effects that require asynchronous handling.

Important: Attempting to run effects that involve asynchronous operations or failures will result in exceptions being thrown, so use this function with care for purely synchronous and error-free effects.

When to Use

Use this function when:

  • You are sure that the effect will not fail or involve asynchronous operations.
  • You need a direct, synchronous result from the effect.
  • You are working within a context where asynchronous effects are not allowed.

Avoid using this function for effects that can fail or require asynchronous handling. For such cases, consider using

runPromise

or

runSyncExit

.

Example (Synchronous Logging)

import { Effect } from "effect"
const program = Effect.sync(() => {
console.log("Hello, World!")
return 1
})
const result = Effect.runSync(program)
// Output: Hello, World!
console.log(result)
// Output: 1

Example (Incorrect Usage with Failing or Async Effects)

import { Effect } from "effect"
try {
// Attempt to run an effect that fails
Effect.runSync(Effect.fail("my error"))
} catch (e) {
console.error(e)
}
// Output:
// (FiberFailure) Error: my error
try {
// Attempt to run an effect that involves async work
Effect.runSync(Effect.promise(() => Promise.resolve(1)))
} catch (e) {
console.error(e)
}
// Output:
// (FiberFailure) AsyncFiberException: Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work

@seerunSyncExit for a version that returns an Exit type instead of throwing an error.

@since2.0.0

runSync
,
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
)
)
)
// Output: Invalid string
// 提供Messages服务以自定义错误消息
import Schema
Schema
.
const decodeUnknownEither: <string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Either.Either<string, ParseResult.ParseError>

@since3.10.0

decodeUnknownEither
(
const Name: Schema.refine<string, typeof Schema.String>
Name
)("").
Pipeable.pipe<Either.Either<string, ParseResult.ParseError>, Either.Either<string, void>>(this: Either.Either<string, ParseResult.ParseError>, ab: (_: Either.Either<string, ParseResult.ParseError>) => Either.Either<string, void>): Either.Either<string, void> (+21 overloads)
pipe
(
import Either

@since2.0.0

@since2.0.0

Either
.
const mapLeft: <ParseResult.ParseError, void>(f: (left: ParseResult.ParseError) => void) => <R>(self: Either.Either<R, ParseResult.ParseError>) => Either.Either<R, void> (+1 overload)

Maps the Left side of an Either value to a new Either value.

@since2.0.0

mapLeft
((
error: ParseResult.ParseError
error
) =>
import ParseResult
ParseResult
.
const TreeFormatter: ParseResult.ParseResultFormatter<string>

@since3.10.0

TreeFormatter
.
ParseResultFormatter<string>.formatError: (error: ParseResult.ParseError) => Effect.Effect<string, never, never>
formatError
(
error: ParseResult.ParseError
error
).
Pipeable.pipe<Effect.Effect<string, never, never>, Effect.Effect<string, never, never>, string, void>(this: Effect.Effect<string, never, never>, ab: (_: Effect.Effect<string, never, never>) => Effect.Effect<string, never, never>, bc: (_: Effect.Effect<string, never, never>) => string, cd: (_: string) => void): void (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const provideService: <Messages, {
NonEmpty: string;
}>(tag: Context.Tag<Messages, {
NonEmpty: string;
}>, service: {
NonEmpty: string;
}) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Messages>> (+1 overload)

Provides an implementation for a service in the context of an effect.

Details

This function allows you to supply a specific implementation for a service required by an effect. Services are typically defined using Context.Tag, which acts as a unique identifier for the service. By using this function, you link the service to its concrete implementation, enabling the effect to execute successfully without additional requirements.

For example, you can use this function to provide a random number generator, a logger, or any other service your effect depends on. Once the service is provided, all parts of the effect that rely on the service will automatically use the implementation you supplied.

Example

import { Effect, Context } from "effect"
// Declaring a tag for a service that generates random numbers
class Random extends Context.Tag("MyRandomService")<
Random,
{ readonly next: Effect.Effect<number> }
>() {}
// Using the service
const program = Effect.gen(function* () {
const random = yield* Random
const randomNumber = yield* random.next
console.log(`random number: ${randomNumber}`)
})
// Providing the implementation
//
// ┌─── Effect<void, never, never>
// ▼
const runnable = Effect.provideService(program, Random, {
next: Effect.sync(() => Math.random())
})
// Run successfully
Effect.runPromise(runnable)
// Example Output:
// random number: 0.8241872233134417

@seeprovide for providing multiple layers to an effect.

@since2.0.0

provideService
(
class Messages
Messages
, {
type NonEmpty: string
NonEmpty
: "should be non empty"
}),
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const runSync: <A, E>(effect: Effect.Effect<A, E>) => A

Executes an effect synchronously, running it immediately and returning the result.

Details

This function evaluates the provided effect synchronously, returning its result directly. It is ideal for effects that do not fail or include asynchronous operations. If the effect does fail or involves async tasks, it will throw an error. Execution stops at the point of failure or asynchronous operation, making it unsuitable for effects that require asynchronous handling.

Important: Attempting to run effects that involve asynchronous operations or failures will result in exceptions being thrown, so use this function with care for purely synchronous and error-free effects.

When to Use

Use this function when:

  • You are sure that the effect will not fail or involve asynchronous operations.
  • You need a direct, synchronous result from the effect.
  • You are working within a context where asynchronous effects are not allowed.

Avoid using this function for effects that can fail or require asynchronous handling. For such cases, consider using

runPromise

or

runSyncExit

.

Example (Synchronous Logging)

import { Effect } from "effect"
const program = Effect.sync(() => {
console.log("Hello, World!")
return 1
})
const result = Effect.runSync(program)
// Output: Hello, World!
console.log(result)
// Output: 1

Example (Incorrect Usage with Failing or Async Effects)

import { Effect } from "effect"
try {
// Attempt to run an effect that fails
Effect.runSync(Effect.fail("my error"))
} catch (e) {
console.error(e)
}
// Output:
// (FiberFailure) Error: my error
try {
// Attempt to run an effect that involves async work
Effect.runSync(Effect.promise(() => Promise.resolve(1)))
} catch (e) {
console.error(e)
}
// Output:
// (FiberFailure) AsyncFiberException: Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work

@seerunSyncExit for a version that returns an Exit type instead of throwing an error.

@since2.0.0

runSync
,
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
)
)
)
// Output: should be non empty

您可以使用missingMessage注解为缺失的字段或元组元素提供自定义消息。

示例(缺失属性的自定义消息)

在此示例中,为Person模式中缺失的name属性定义了自定义消息。

import {
import Schema
Schema
} from "effect"
const
const Person: Schema.Struct<{
name: Schema.propertySignature<typeof Schema.String>;
}>
Person
=
import Schema
Schema
.
function Struct<{
name: Schema.propertySignature<typeof Schema.String>;
}>(fields: {
name: Schema.propertySignature<typeof Schema.String>;
}): Schema.Struct<{
name: Schema.propertySignature<typeof Schema.String>;
}> (+1 overload)

@since3.10.0

Struct
({
name: Schema.propertySignature<typeof Schema.String>
name
:
import Schema
Schema
.
const propertySignature: <typeof Schema.String>(self: typeof Schema.String) => Schema.propertySignature<typeof Schema.String>

Lifts a Schema into a PropertySignature.

@since3.10.0

propertySignature
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
).
propertySignature<typeof String$>.annotations(annotations: Schema.PropertySignature<TypeToken extends Schema.PropertySignature.Token, Type, Key extends PropertyKey, EncodedToken extends Schema.PropertySignature.Token, Encoded, HasDefault extends boolean = false, R = never>.Annotations<string>): Schema.propertySignature<typeof Schema.String>
annotations
({
// 如果"name"缺失的自定义消息
PropertySignature<TypeToken extends PropertySignature.Token, Type, Key extends PropertyKey, EncodedToken extends PropertySignature.Token, Encoded, HasDefault extends boolean = false, R = never>.Annotations<string>.missingMessage?: MissingMessageAnnotation
missingMessage
: () => "Name is required"
})
})
import Schema
Schema
.
decodeUnknownSync<{
readonly name: string;
}, {
readonly name: string;
}>(schema: Schema.Schema<{
readonly name: string;
}, {
readonly name: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: Schema.propertySignature<typeof Schema.String>;
}>
Person
)({})
/*
throws:
ParseError: { readonly name: string }
└─ ["name"]
└─ Name is required
*/

示例(缺失元组元素的自定义消息)

在这里,Point元组模式中的每个元素在元素缺失时都有特定的自定义消息。

import {
import Schema
Schema
} from "effect"
const
const Point: Schema.Tuple<[Schema.Element<typeof Schema.Number, "">, Schema.Element<typeof Schema.Number, "">]>
Point
=
import Schema
Schema
.
function Tuple<[Schema.Element<typeof Schema.Number, "">, Schema.Element<typeof Schema.Number, "">]>(elements_0: Schema.Element<typeof Schema.Number, "">, elements_1: Schema.Element<typeof Schema.Number, "">): Schema.Tuple<[Schema.Element<typeof Schema.Number, "">, Schema.Element<typeof Schema.Number, "">]> (+2 overloads)

@since3.10.0

Tuple
(
import Schema
Schema
.
const element: <typeof Schema.Number>(self: typeof Schema.Number) => Schema.Element<typeof Schema.Number, "">

@since3.10.0

element
(
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
).
Element<typeof Number$, "">.annotations(annotations: Schema.Element<S extends Schema.Schema<in out A, in out I = A, out R = never>.Any, Token extends Schema.Element.Token>.Annotations<number>): Schema.Element<typeof Schema.Number, "">
annotations
({
// 如果X缺失的消息
Element<S extends Schema<in out A, in out I = A, out R = never>.Any, Token extends Element.Token>.Annotations<number>.missingMessage?: MissingMessageAnnotation
missingMessage
: () => "X coordinate is required"
}),
import Schema
Schema
.
const element: <typeof Schema.Number>(self: typeof Schema.Number) => Schema.Element<typeof Schema.Number, "">

@since3.10.0

element
(
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
).
Element<typeof Number$, "">.annotations(annotations: Schema.Element<S extends Schema.Schema<in out A, in out I = A, out R = never>.Any, Token extends Schema.Element.Token>.Annotations<number>): Schema.Element<typeof Schema.Number, "">
annotations
({
// 如果Y缺失的消息
Element<S extends Schema<in out A, in out I = A, out R = never>.Any, Token extends Element.Token>.Annotations<number>.missingMessage?: MissingMessageAnnotation
missingMessage
: () => "Y coordinate is required"
})
)
import Schema
Schema
.
decodeUnknownSync<readonly [number, number], readonly [number, number]>(schema: Schema.Schema<readonly [number, number], readonly [number, number], never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => readonly [number, number]
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Point: Schema.Tuple<[Schema.Element<typeof Schema.Number, "">, Schema.Element<typeof Schema.Number, "">]>
Point
)([], {
ParseOptions.errors?: "first" | "all" | undefined

The errors option allows you to receive all parsing errors when attempting to parse a value using a schema. By default only the first error is returned, but by setting the errors option to "all", you can receive all errors that occurred during the parsing process. This can be useful for debugging or for providing more comprehensive error messages to the user.

default: "first"

@since3.10.0

errors
: "all" })
/*
throws:
ParseError: readonly [number, number]
├─ [0]
│ └─ X coordinate is required
└─ [1]
└─ Y coordinate is required
*/