Skip to content

类 API

在使用模式时,除了Schema.Struct构造器之外,您还有其他选择。 您可以通过Schema.Class实用程序利用类的强大功能,它具有针对常见用例量身定制的一系列优势:

类提供了几个简化模式创建过程的功能:

  • 一体化定义:使用类,您可以同时定义模式和不透明类型。
  • 共享功能:您可以使用类方法或getter合并共享功能。
  • 值哈希和等值:利用内置功能检查值等值和应用哈希(感谢Class实现了Data.Class)。

要使用Schema.Class定义类,您需要指定:

  • 正在创建的类的类型
  • 类的唯一标识符
  • 所需的字段

示例(定义模式类)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}

在此示例中,Person既是模式又是TypeScript类。Person的实例使用定义的模式创建,确保符合指定的字段。

示例(创建实例)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(new
constructor Person(props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John" }))
/*
Output:
Person { id: 1, name: 'John' }
*/
// 使用工厂函数
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
(
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.make<typeof Person>(this: typeof Person, props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions | undefined): Person
make
({
id: number
id
: 1,
name: string
name
: "John" }))
/*
Output:
Person { id: 1, name: 'John' }
*/

类模式将结构模式转换为表示类类型的声明模式。

  • 解码时,普通对象被转换为类的实例。
  • 编码时,类实例被转换回普通对象。

示例(解码和编码类)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}
const
const person: Person
person
=
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.make<typeof Person>(this: typeof Person, props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions | undefined): Person
make
({
id: number
id
: 1,
name: string
name
: "John" })
// 从普通对象解码为类实例
const
const decoded: Person
decoded
=
import Schema
Schema
.
decodeUnknownSync<Person, {
readonly id: number;
readonly name: string;
}>(schema: Schema.Schema<Person, {
readonly id: number;
readonly name: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => Person
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
class Person
Person
)({
id: number
id
: 1,
name: string
name
: "John" })
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decoded: Person
decoded
)
// Output: Person { id: 1, name: 'John' }
// 将类实例编码回普通对象
const
const encoded: {
readonly id: number;
readonly name: string;
}
encoded
=
import Schema
Schema
.
encodeUnknownSync<Person, {
readonly id: number;
readonly name: string;
}>(schema: Schema.Schema<Person, {
readonly id: number;
readonly name: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly id: number;
readonly name: string;
}
export encodeUnknownSync

@throwsParseError

@since3.10.0

encodeUnknownSync
(
class Person
Person
)(
const person: Person
person
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const encoded: {
readonly id: number;
readonly name: string;
}
encoded
)
// Output: { id: 1, name: 'John' }

当您的模式不需要任何字段时,您可以使用空对象定义类。

示例(定义和使用无参数的类)

import {
import Schema
Schema
} from "effect"
// 定义无字段的类
class
class NoArgs
NoArgs
extends
import Schema
Schema
.
const Class: <NoArgs>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<NoArgs, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<NoArgs, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class NoArgs
NoArgs
>("NoArgs")({}) {}
// 使用默认构造器创建实例
const
const noargs1: NoArgs
noargs1
= new
constructor NoArgs(props: void | {}, options?: Schema.MakeOptions): NoArgs
NoArgs
()
// 或者,通过显式传递空对象创建实例
const
const noargs2: NoArgs
noargs2
= new
constructor NoArgs(props: void | {}, options?: Schema.MakeOptions): NoArgs
NoArgs
({})

过滤器允许您在解码、编码或创建实例时验证输入。您可以传递应用了过滤器的Schema.Struct,而不是指定原始字段。

示例(对模式类应用过滤器)

import {
import Schema
Schema
} from "effect"
class
class WithFilter
WithFilter
extends
import Schema
Schema
.
const Class: <WithFilter>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<WithFilter, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<WithFilter, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<...>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class WithFilter
WithFilter
>("WithFilter")(
import Schema
Schema
.
function Struct<{
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}>(fields: {
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}): Schema.Struct<{
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}> (+1 overload)

@since3.10.0

Struct
({
a: typeof Schema.NumberFromString
a
:
import Schema
Schema
.
class NumberFromString

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

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

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

@since3.10.0

NumberFromString
,
b: typeof Schema.NumberFromString
b
:
import Schema
Schema
.
class NumberFromString

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

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

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

@since3.10.0

NumberFromString
}).
Pipeable.pipe<Schema.Struct<{
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}>, Schema.filter<Schema.Struct<{
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}>>>(this: Schema.Struct<{
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}>, ab: (_: Schema.Struct<{
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}>) => Schema.filter<Schema.Struct<{
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}>>): Schema.filter<...> (+21 overloads)
pipe
(
import Schema
Schema
.
function filter<Schema.Struct<{
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}>>(predicate: (a: {
readonly a: number;
readonly b: number;
}, options: ParseOptions, self: Refinement) => FilterReturnType, annotations?: Schema.Annotations.Filter<{
readonly a: number;
readonly b: number;
}, {
readonly a: number;
readonly b: number;
}> | undefined): (self: Schema.Struct<{
a: typeof Schema.NumberFromString;
b: typeof Schema.NumberFromString;
}>) => Schema.filter<...> (+2 overloads)

@since3.10.0

filter
(({
a: number
a
,
b: number
b
}) =>
a: number
a
>=
b: number
b
|| "a must be greater than b")
)
) {}
// 构造器
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(new
constructor WithFilter(props: {
readonly a: number;
readonly b: number;
}, options?: Schema.MakeOptions): WithFilter
WithFilter
({
a: number
a
: 1,
b: number
b
: 2 }))
/*
throws:
ParseError: WithFilter (Constructor)
└─ Predicate refinement failure
└─ a must be greater than b
*/
// 解码
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<WithFilter, {
readonly a: string;
readonly b: string;
}>(schema: Schema.Schema<WithFilter, {
readonly a: string;
readonly b: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => WithFilter
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
class WithFilter
WithFilter
)({
a: string
a
: "1",
b: string
b
: "2" }))
/*
throws:
ParseError: (WithFilter (Encoded side) <-> WithFilter)
└─ Encoded side transformation failure
└─ WithFilter (Encoded side)
└─ Predicate refinement failure
└─ a must be greater than b
*/

当您使用Schema.Class定义类时,构造器会自动检查提供的属性是否符合模式的规则。

构造器确保每个属性(如idname)都符合模式。例如,id必须是数字,name必须是非空字符串。

示例(创建有效实例)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}
// 使用有效属性创建实例
const
const john: Person
john
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John" })

如果在实例化期间提供了无效属性,构造器会抛出错误,解释验证失败的原因。

示例(使用无效属性创建实例)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}
// 尝试使用无效的`name`创建实例
new
constructor Person(props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "" })
/*
throws:
ParseError: Person (Constructor)
└─ ["name"]
└─ NonEmptyString
└─ Predicate refinement failure
└─ Expected NonEmptyString, actual ""
*/

错误清楚地指出name字段未能满足NonEmptyString要求。

在某些情况下,您可能希望绕过验证逻辑。虽然通常不建议这样做,但库提供了这样做的选项。

示例(绕过验证)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}
// 在实例化期间绕过验证
const
const john: Person
john
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "" }, true)
// 或显式使用`disableValidation`选项
new
constructor Person(props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "" }, {
disableValidation?: boolean | undefined
disableValidation
: true })

使用Schema.Class创建的类实例通过与Data.Class的集成支持Equal特征。这使得即使在不同实例之间也能进行直接的值比较。

如果两个类实例的属性具有相同的值,则认为它们相等。

示例(比较具有相等属性的实例)

import {
import Schema
Schema
} from "effect"
import {
import Equal
Equal
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}
const
const john1: Person
john1
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John" })
const
const john2: Person
john2
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John" })
// 比较实例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Equal
Equal
.
function equals<Person, Person>(self: Person, that: Person): boolean (+1 overload)

@since2.0.0

equals
(
const john1: Person
john1
,
const john2: Person
john2
))
// Output: true

Equal特征在第一级执行比较。如果属性是更复杂的结构(如数组),即使数组本身具有相同的值,实例也可能不被认为相等。

示例(数组的浅等值)

import {
import Schema
Schema
} from "effect"
import {
import Equal
Equal
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
,
hobbies: Schema.Array$<typeof Schema.String>
hobbies
:
import Schema
Schema
.
Array<typeof Schema.String>(value: typeof Schema.String): Schema.Array$<typeof Schema.String>
export Array

@since3.10.0

Array
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
) // 标准数组模式
}) {}
const
const john1: Person
john1
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
readonly hobbies: readonly string[];
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John",
hobbies: readonly string[]
hobbies
: ["reading", "coding"]
})
const
const john2: Person
john2
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
readonly hobbies: readonly string[];
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John",
hobbies: readonly string[]
hobbies
: ["reading", "coding"]
})
// 等值失败,因为`hobbies`没有进行深度比较
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Equal
Equal
.
function equals<Person, Person>(self: Person, that: Person): boolean (+1 overload)

@since2.0.0

equals
(
const john1: Person
john1
,
const john2: Person
john2
))
// Output: false

要为数组等嵌套结构实现深度等值,请结合使用Schema.DataData.array。这使库能够比较数组的每个元素,而不是将其视为单个实体。

示例(使用Schema.Data进行深度等值)

import {
import Schema
Schema
} from "effect"
import {
import Data
Data
,
import Equal
Equal
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
,
hobbies: Schema.Data<Schema.Array$<typeof Schema.String>>
hobbies
:
import Schema
Schema
.
const Data: <Schema.Array$<typeof Schema.String>, readonly string[], readonly string[]>(value: Schema.Array$<typeof Schema.String> & Schema.Schema<readonly string[], readonly string[], never>) => Schema.Data<Schema.Array$<typeof Schema.String>>

Type and Encoded must extend Readonly<Record<string, any>> | ReadonlyArray<any> to be compatible with this API.

@since3.10.0

Data
(
import Schema
Schema
.
Array<typeof Schema.String>(value: typeof Schema.String): Schema.Array$<typeof Schema.String>
export Array

@since3.10.0

Array
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
)) // 启用深度等值
}) {}
const
const john1: Person
john1
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
readonly hobbies: readonly string[];
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John",
hobbies: readonly string[]
hobbies
:
import Data
Data
.
const array: <string[]>(as: string[]) => readonly string[]

@example

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

@since2.0.0

array
(["reading", "coding"])
})
const
const john2: Person
john2
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
readonly hobbies: readonly string[];
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John",
hobbies: readonly string[]
hobbies
:
import Data
Data
.
const array: <string[]>(as: string[]) => readonly string[]

@example

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

@since2.0.0

array
(["reading", "coding"])
})
// 等值成功,因为`hobbies`进行了深度比较
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Equal
Equal
.
function equals<Person, Person>(self: Person, that: Person): boolean (+1 overload)

@since2.0.0

equals
(
const john1: Person
john1
,
const john2: Person
john2
))
// Output: true

模式类提供了包含自定义getter和方法的灵活性,允许您将其功能扩展到定义字段之外。

getter可用于从类的字段派生计算值。例如,Person类可以包含一个getter来返回大写的name属性。

示例(为大写名称添加Getter)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {
// 返回大写名称的自定义getter
get
Person.upperName: string
upperName
() {
return this.
name: string
name
.
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
()
}
}
const
const john: Person
john
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John" })
// 使用自定义getter
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const john: Person
john
.
Person.upperName: string
upperName
)
// Output: "JOHN"

除了getter之外,您还可以定义方法来封装涉及类字段的更复杂逻辑或操作。

示例(添加方法)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {
// 返回问候语的自定义方法
Person.greet(): string
greet
() {
return `Hello, my name is ${this.
name: string
name
}.`
}
}
const
const john: Person
john
= new
constructor Person(props: {
readonly id: number;
readonly name: string;
}, options?: Schema.MakeOptions): Person
Person
({
id: number
id
: 1,
name: string
name
: "John" })
// 使用自定义方法
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const john: Person
john
.
Person.greet(): string
greet
())
// Output: "Hello, my name is John."

当您使用Schema.Class定义类时,它既作为模式又作为类。这种双重功能允许在需要模式的任何地方使用该类。

示例(在数组模式中使用类)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}
// 在数组模式中使用Person类
const
const Persons: Schema.Array$<typeof Person>
Persons
=
import Schema
Schema
.
Array<typeof Person>(value: typeof Person): Schema.Array$<typeof Person>
export Array

@since3.10.0

Array
(
class Person
Person
)
// ┌─── readonly Person[]
// ▼
type
type Type = readonly Person[]
Type
= typeof
const Persons: Schema.Array$<typeof Person>
Persons
.
Schema<readonly Person[], readonly { readonly id: number; readonly name: string; }[], never>.Type: readonly Person[]
Type

类还包含一个fields静态属性,它概述了在类创建期间定义的字段。

示例(访问fields属性)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}
// ┌─── {
// | readonly id: typeof Schema.Number;
// | readonly name: typeof Schema.NonEmptyString;
// | }
// ▼
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.fields: {
readonly id: typeof Schema.Number;
readonly name: typeof Schema.NonEmptyString;
}
fields

使用Schema.Class定义类类似于创建转换模式,该模式将结构模式转换为表示类类型的声明模式。

例如,考虑以下类定义:

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}

在底层,此定义创建了一个转换模式,该模式映射:

Schema.Struct({
id: Schema.Number,
name: Schema.NonEmptyString
})

到表示Person类的模式:

Schema.declare((input) => input instanceof Person)

因此,使用Schema.Class定义模式涉及三个模式:

  • “from”模式(结构)
  • “to”模式(类)
  • “transformation”模式(结构 -> 类)

您可以通过将元组作为第二个参数传递给Schema.Class API来注解这些模式中的每一个。

示例(注解类模式的不同部分)

import {
import Schema
Schema
,
import SchemaAST
SchemaAST
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")(
{
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
},
[
// "to"模式的注解
{
Annotations.Doc<Person>.description?: string
description
: `"to" description` },
// "transformation"模式的注解
{
Annotations.Doc<Person>.description?: string
description
: `"transformation" description` },
// "from"模式的注解
{
Annotations.Doc<A>.description?: string
description
: `"from" description` }
]
) {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import SchemaAST
SchemaAST
.
const getDescriptionAnnotation: (annotated: SchemaAST.Annotated) => Option<string>

@since3.10.0

getDescriptionAnnotation
(
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.ast: SchemaAST.Transformation

@since3.10.0

ast
.
Transformation.to: SchemaAST.AST
to
))
// Output: { _id: 'Option', _tag: 'Some', value: '"to" description' }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import SchemaAST
SchemaAST
.
const getDescriptionAnnotation: (annotated: SchemaAST.Annotated) => Option<string>

@since3.10.0

getDescriptionAnnotation
(
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.ast: SchemaAST.Transformation

@since3.10.0

ast
))
// Output: { _id: 'Option', _tag: 'Some', value: '"transformation" description' }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import SchemaAST
SchemaAST
.
const getDescriptionAnnotation: (annotated: SchemaAST.Annotated) => Option<string>

@since3.10.0

getDescriptionAnnotation
(
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.ast: SchemaAST.Transformation

@since3.10.0

ast
.
Transformation.from: SchemaAST.AST
from
))
// Output: { _id: 'Option', _tag: 'Some', value: '"from" description' }

如果您不想注解所有三个模式,可以为希望跳过的模式传递undefined

示例(跳过注解)

import {
import Schema
Schema
,
import SchemaAST
SchemaAST
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")(
{
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
},
[
// "to"模式无注解
var undefined
undefined
,
// "transformation"模式的注解
{
Annotations.Doc<Person>.description?: string
description
: `"transformation" description` }
]
) {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import SchemaAST
SchemaAST
.
const getDescriptionAnnotation: (annotated: SchemaAST.Annotated) => Option<string>

@since3.10.0

getDescriptionAnnotation
(
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.ast: SchemaAST.Transformation

@since3.10.0

ast
.
Transformation.to: SchemaAST.AST
to
))
// Output: { _id: 'Option', _tag: 'None' }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import SchemaAST
SchemaAST
.
const getDescriptionAnnotation: (annotated: SchemaAST.Annotated) => Option<string>

@since3.10.0

getDescriptionAnnotation
(
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.ast: SchemaAST.Transformation

@since3.10.0

ast
))
// Output: { _id: 'Option', _tag: 'Some', value: '"transformation" description' }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import SchemaAST
SchemaAST
.
const getDescriptionAnnotation: (annotated: SchemaAST.Annotated) => Option<string>

@since3.10.0

getDescriptionAnnotation
(
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.ast: SchemaAST.Transformation

@since3.10.0

ast
.
Transformation.from: SchemaAST.AST
from
))
// Output: { _id: 'Option', _tag: 'None' }

默认情况下,用于定义类的唯一标识符也作为类模式的默认identifier注解应用。

示例(默认标识符注解)

import {
import Schema
Schema
,
import SchemaAST
SchemaAST
} from "effect"
// 用作默认标识符注解 ────┐
// |
// ▼
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import SchemaAST
SchemaAST
.
const getIdentifierAnnotation: (annotated: SchemaAST.Annotated) => Option<string>

@since3.10.0

getIdentifierAnnotation
(
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.ast: SchemaAST.Transformation

@since3.10.0

ast
.
Transformation.to: SchemaAST.AST
to
))
// Output: { _id: 'Option', _tag: 'Some', value: 'Person' }

当您需要定义依赖于自身的模式时,Schema.suspend组合器很有用,就像递归数据结构的情况一样。 在此示例中,Category模式依赖于自身,因为它有一个subcategories字段,该字段是Category对象的数组。

示例(自引用模式)

import {
import Schema
Schema
} from "effect"
// 定义具有递归子类别字段的Category模式
class
class Category
Category
extends
import Schema
Schema
.
const Class: <Category>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Category, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Category, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<...>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Category
Category
>("Category")({
name: typeof Schema.String
name
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>
subcategories
:
import Schema
Schema
.
Array<Schema.suspend<Category, Category, never>>(value: Schema.suspend<Category, Category, never>): Schema.Array$<Schema.suspend<Category, Category, never>>
export Array

@since3.10.0

Array
(
import Schema
Schema
.
const suspend: <Category, Category, never>(f: () => Schema.Schema<Category, Category, never>) => Schema.suspend<Category, Category, never>

@since3.10.0

suspend
(():
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never>

@since3.10.0

@since3.10.0

Schema
<
class Category
Category
> =>
class Category
Category
)
)
}) {}

示例(缺少类型注解错误)

import {
import Schema
Schema
} from "effect"
class Category extends
import Schema
Schema
.
const Class: <Category>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Category, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Category, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<...>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Category
Category
>("Category")({
Error ts(2506) ― 'Category' is referenced directly or indirectly in its own base expression.
name: typeof Schema.String
name
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
subcategories: Schema.Array$<Schema.suspend<unknown, unknown, unknown>>
subcategories
:
import Schema
Schema
.
Array<Schema.suspend<unknown, unknown, unknown>>(value: Schema.suspend<unknown, unknown, unknown>): Schema.Array$<Schema.suspend<unknown, unknown, unknown>>
export Array

@since3.10.0

Array
(
import Schema
Schema
.
const suspend: <unknown, unknown, unknown>(f: () => Schema.Schema<unknown, unknown, unknown>) => Schema.suspend<unknown, unknown, unknown>

@since3.10.0

suspend
(() =>
class Category
Category
))
Error ts(7024) ― Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions.
}) {}

有时,模式以互相递归的方式相互依赖。例如,算术表达式树可能包括Expression节点,这些节点可以是数字或Operation节点,而Operation节点又引用Expression节点。

示例(算术表达式树)

import {
import Schema
Schema
} from "effect"
class
class Expression
Expression
extends
import Schema
Schema
.
const Class: <Expression>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Expression, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Expression, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<...>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Expression
Expression
>("Expression")({
type: Schema.Literal<["expression"]>
type
:
import Schema
Schema
.
function Literal<["expression"]>(literals_0: "expression"): Schema.Literal<["expression"]> (+2 overloads)

@since3.10.0

Literal
("expression"),
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>
value
:
import Schema
Schema
.
function Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>(members_0: typeof Schema.Number, members_1: Schema.suspend<Operation, Operation, never>): Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]> (+3 overloads)

@since3.10.0

Union
(
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
import Schema
Schema
.
const suspend: <Operation, Operation, never>(f: () => Schema.Schema<Operation, Operation, never>) => Schema.suspend<Operation, Operation, never>

@since3.10.0

suspend
(():
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never>

@since3.10.0

@since3.10.0

Schema
<
class Operation
Operation
> =>
class Operation
Operation
)
)
}) {}
class
class Operation
Operation
extends
import Schema
Schema
.
const Class: <Operation>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Operation, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Operation, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<...>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Operation
Operation
>("Operation")({
type: Schema.Literal<["operation"]>
type
:
import Schema
Schema
.
function Literal<["operation"]>(literals_0: "operation"): Schema.Literal<["operation"]> (+2 overloads)

@since3.10.0

Literal
("operation"),
operator: Schema.Literal<["+", "-"]>
operator
:
import Schema
Schema
.
function Literal<["+", "-"]>(literals_0: "+", literals_1: "-"): Schema.Literal<["+", "-"]> (+2 overloads)

@since3.10.0

Literal
("+", "-"),
left: typeof Expression
left
:
class Expression
Expression
,
right: typeof Expression
right
:
class Expression
Expression
}) {}

定义Encoded类型与Type类型不同的递归模式会引入额外的复杂性。例如,如果模式包含转换数据的字段(例如NumberFromString),则EncodedType类型可能不对齐。

在这种情况下,我们需要为Encoded类型定义接口。

让我们考虑一个示例:假设我们想要向Category模式添加一个id字段,其中id的模式是NumberFromString。 重要的是要注意NumberFromString是一个将字符串转换为数字的模式,因此NumberFromStringTypeEncoded类型不同,分别为numberstring。 当我们将此字段添加到Category模式时,TypeScript会引发错误:

import {
import Schema
Schema
} from "effect"
class
class Category
Category
extends
import Schema
Schema
.
const Class: <Category>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Category, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Category, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<...>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Category
Category
>("Category")({
id: typeof Schema.NumberFromString
id
:
import Schema
Schema
.
class NumberFromString

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

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

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

@since3.10.0

NumberFromString
,
name: typeof Schema.String
name
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>
subcategories
:
import Schema
Schema
.
Array<Schema.suspend<Category, Category, never>>(value: Schema.suspend<Category, Category, never>): Schema.Array$<Schema.suspend<Category, Category, never>>
export Array

@since3.10.0

Array
(
import Schema
Schema
.
const suspend: <Category, Category, never>(f: () => Schema.Schema<Category, Category, never>) => Schema.suspend<Category, Category, never>

@since3.10.0

suspend
(():
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never>

@since3.10.0

@since3.10.0

Schema
<
class Category
Category
> => Category)
Error ts(2322) ― Type 'typeof Category' is not assignable to type 'Schema<Category, Category, never>'. The types of 'Encoded.id' are incompatible between these types. Type 'string' is not assignable to type 'number'.
)
}) {}

此错误发生是因为显式注解S.suspend((): S.Schema<Category> => Category不再足够,需要通过显式添加Encoded类型来调整:

示例(使用显式Encoded类型调整模式)

import {
import Schema
Schema
} from "effect"
interface
interface CategoryEncoded
CategoryEncoded
{
readonly
CategoryEncoded.id: string
id
: string
readonly
CategoryEncoded.name: string
name
: string
readonly
CategoryEncoded.subcategories: readonly CategoryEncoded[]
subcategories
:
interface ReadonlyArray<T>
ReadonlyArray
<
interface CategoryEncoded
CategoryEncoded
>
}
class
class Category
Category
extends
import Schema
Schema
.
const Class: <Category>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Category, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Category, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<...>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Category
Category
>("Category")({
id: typeof Schema.NumberFromString
id
:
import Schema
Schema
.
class NumberFromString

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

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

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

@since3.10.0

NumberFromString
,
name: typeof Schema.String
name
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
subcategories: Schema.Array$<Schema.suspend<Category, CategoryEncoded, never>>
subcategories
:
import Schema
Schema
.
Array<Schema.suspend<Category, CategoryEncoded, never>>(value: Schema.suspend<Category, CategoryEncoded, never>): Schema.Array$<Schema.suspend<Category, CategoryEncoded, never>>
export Array

@since3.10.0

Array
(
import Schema
Schema
.
const suspend: <Category, CategoryEncoded, never>(f: () => Schema.Schema<Category, CategoryEncoded, never>) => Schema.suspend<Category, CategoryEncoded, never>

@since3.10.0

suspend
(
():
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never>

@since3.10.0

@since3.10.0

Schema
<
class Category
Category
,
interface CategoryEncoded
CategoryEncoded
> =>
class Category
Category
)
)
}) {}

正如我们所观察到的,有必要为模式的Encoded定义接口以启用递归模式定义,这可能会使事情复杂化并且相当繁琐。 缓解这种情况的一种模式是将负责递归的字段与所有其他字段分离

示例(分离递归字段)

import {
import Schema
Schema
} from "effect"
const
const fields: {
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}
fields
= {
id: typeof Schema.NumberFromString
id
:
import Schema
Schema
.
class NumberFromString

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

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

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

@since3.10.0

NumberFromString
,
name: typeof Schema.String
name
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
// ...可能的其他字段
}
interface
interface CategoryEncoded
CategoryEncoded
extends
import Schema
Schema
.
namespace Struct

@since3.10.0

@since3.10.0

@since3.10.0

Struct
.
type Struct<Fields extends Struct.Fields>.Encoded<F extends Schema.Struct.Fields> = { readonly [K in Exclude<keyof F, Schema.Struct.EncodedOptionalKeys<F>> as Schema.Struct.Key<F, K>]: Schema.Schema.Encoded<F[K]>; } & { readonly [K in Schema.Struct.EncodedOptionalKeys<F> as Schema.Struct.Key<F, K>]?: Schema.Schema.Encoded<F[K]>; }

@since3.10.0

Encoded
<typeof
const fields: {
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}
fields
> {
// 使用递归定义`subcategories`
readonly
CategoryEncoded.subcategories: readonly CategoryEncoded[]
subcategories
:
interface ReadonlyArray<T>
ReadonlyArray
<
interface CategoryEncoded
CategoryEncoded
>
}
class
class Category
Category
extends
import Schema
Schema
.
const Class: <Category>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Category, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Category, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<...>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Category
Category
>("Category")({
...
const fields: {
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}
fields
, // 包含字段
subcategories: Schema.Array$<Schema.suspend<Category, CategoryEncoded, never>>
subcategories
:
import Schema
Schema
.
Array<Schema.suspend<Category, CategoryEncoded, never>>(value: Schema.suspend<Category, CategoryEncoded, never>): Schema.Array$<Schema.suspend<Category, CategoryEncoded, never>>
export Array

@since3.10.0

Array
(
// 使用递归定义`subcategories`
import Schema
Schema
.
const suspend: <Category, CategoryEncoded, never>(f: () => Schema.Schema<Category, CategoryEncoded, never>) => Schema.suspend<Category, CategoryEncoded, never>

@since3.10.0

suspend
(
():
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never>

@since3.10.0

@since3.10.0

Schema
<
class Category
Category
,
interface CategoryEncoded
CategoryEncoded
> =>
class Category
Category
)
)
}) {}

您还可以创建扩展effect/Data模块中的TaggedClassTaggedError的类。

示例(创建标记类和错误)

import {
import Schema
Schema
} from "effect"
// 定义具有"name"字段的标记类
class
class TaggedPerson
TaggedPerson
extends
import Schema
Schema
.
const TaggedClass: <TaggedPerson>(identifier?: string) => <Tag, Fields>(tag: Tag, fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<TaggedPerson, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<{
readonly _tag: Schema.tag<Tag>;
} & Fields>]: Schema.Struct.Type<{
readonly _tag: Schema.tag<Tag>;
} & Fields>[K]; }> | undefined) => Schema.TaggedClass<TaggedPerson, Tag, {
...;
} & Fields>

@example

import { Schema } from "effect"
class MyClass extends Schema.TaggedClass<MyClass>("MyClass")("MyClass", {
a: Schema.String
}) {}

@since3.10.0

TaggedClass
<
class TaggedPerson
TaggedPerson
>()(
"TaggedPerson",
{
name: typeof Schema.String
name
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
}
) {}
// 定义具有"status"字段的标记错误
class
class HttpError
HttpError
extends
import Schema
Schema
.
const TaggedError: <HttpError>(identifier?: string) => <Tag, Fields>(tag: Tag, fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<HttpError, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<{
readonly _tag: Schema.tag<Tag>;
} & Fields>]: Schema.Struct.Type<{
readonly _tag: Schema.tag<Tag>;
} & Fields>[K]; }> | undefined) => Schema.TaggedErrorClass<HttpError, Tag, {
...;
} & Fields>

@example

import { Schema } from "effect"
class MyError extends Schema.TaggedError<MyError>("MyError")(
"MyError",
{
module: Schema.String,
method: Schema.String,
description: Schema.String
}
) {
get message(): string {
return `${this.module}.${this.method}: ${this.description}`
}
}

@since3.10.0

TaggedError
<
class HttpError
HttpError
>()("HttpError", {
status: typeof Schema.Number
status
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
}) {}
const
const joe: TaggedPerson
joe
= new
constructor TaggedPerson(props: {
readonly name: string;
}, options?: Schema.MakeOptions): TaggedPerson
TaggedPerson
({
name: string
name
: "Joe" })
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const joe: TaggedPerson
joe
.
_tag: "TaggedPerson"
_tag
)
// Output: "TaggedPerson"
const
const error: HttpError
error
= new
constructor HttpError(props: {
readonly status: number;
}, options?: Schema.MakeOptions): HttpError
HttpError
({
status: number
status
: 404 })
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const error: HttpError
error
.
_tag: "HttpError"
_tag
)
// Output: "HttpError"
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const error: HttpError
error
.
Error.stack?: string | undefined
stack
) // 访问堆栈跟踪

extend静态实用程序允许您通过添加额外字段和功能来增强现有的模式类。这种方法有助于在现有模式的基础上构建,而无需从头重新定义它们。

示例(扩展模式类)

import {
import Schema
Schema
} from "effect"
// 定义基类
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {
// 将名称转换为大写的自定义getter
get
Person.upperName: string
upperName
() {
return this.
name: string
name
.
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
()
}
}
// 扩展基类以包含"age"字段
class
class PersonWithAge
PersonWithAge
extends
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.extend<PersonWithAge>(identifier: string): <NewFields>(fields: NewFields | HasFields<NewFields>, annotations?: ClassAnnotations<PersonWithAge, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<{
id: typeof Schema.Number;
name: typeof Schema.NonEmptyString;
} & NewFields>]: Schema.Struct.Type<{
id: typeof Schema.Number;
name: typeof Schema.NonEmptyString;
} & NewFields>[K]; }> | undefined) => Schema.Class<...>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
myField: Schema.String
}) {
myMethod() {
return this.myField + "my"
}
}
class NextClass extends MyClass.extend<NextClass>("NextClass")({
nextField: Schema.Number
}) {
nextMethod() {
return this.myMethod() + this.myField + this.nextField
}
}

extend
<
class PersonWithAge
PersonWithAge
>("PersonWithAge")(
{
age: typeof Schema.Number
age
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
}
) {
// 检查人员是否为成年人的自定义getter
get
PersonWithAge.isAdult: boolean
isAdult
() {
return this.
age: number
age
>= 18
}
}
// 用法
const
const john: PersonWithAge
john
= new
constructor PersonWithAge(props: {
readonly id: number;
readonly name: string;
readonly age: number;
}, options?: Schema.MakeOptions): PersonWithAge
PersonWithAge
({
id: number
id
: 1,
name: string
name
: "John",
age: number
age
: 25 })
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const john: PersonWithAge
john
.
Person.upperName: string
upperName
) // Output: "JOHN"
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const john: PersonWithAge
john
.
PersonWithAge.isAdult: boolean
isAdult
) // Output: true

请注意,扩展类时只能添加额外字段。

示例(尝试覆盖现有字段)

import {
import Schema
Schema
} from "effect"
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}) {
get
Person.upperName: string
upperName
() {
return this.
name: string
name
.
String.toUpperCase(): string

Converts all the alphabetic characters in a string to uppercase.

toUpperCase
()
}
}
class
class BadExtension
BadExtension
extends
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof NonEmptyString; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof NonEmptyString; }>, never, { ...; } & { ...; }, {}, {}>.extend<BadExtension>(identifier: string): <NewFields>(fields: NewFields | HasFields<NewFields>, annotations?: ClassAnnotations<BadExtension, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<{
id: typeof Schema.Number;
name: typeof Schema.NonEmptyString;
} & NewFields>]: Schema.Struct.Type<{
id: typeof Schema.Number;
name: typeof Schema.NonEmptyString;
} & NewFields>[K]; }> | undefined) => Schema.Class<...>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
myField: Schema.String
}) {
myMethod() {
return this.myField + "my"
}
}
class NextClass extends MyClass.extend<NextClass>("NextClass")({
nextField: Schema.Number
}) {
nextMethod() {
return this.myMethod() + this.myField + this.nextField
}
}

extend
<
class BadExtension
BadExtension
>("BadExtension")({
name: typeof Schema.Number
name
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
}) {}
/*
throws:
Error: Duplicate property signature
details: Duplicate key "name"
*/

此错误发生是因为允许覆盖字段是不安全的。它可能会干扰类上定义的任何依赖于原始定义的getter或方法。例如,在这种情况下,如果name字段更改为数字,upperName getter将会中断。

您可以使用有效转换来增强模式类,以丰富或验证实体,特别是在处理来自数据库或API等外部系统的数据时。

示例(有效转换)

以下示例演示了向Person类添加age字段。age值基于id字段异步派生。

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Option

@since2.0.0

@since2.0.0

Option
,
import Schema
Schema
,
import ParseResult
ParseResult
} from "effect"
// 基类定义
class
class Person
Person
extends
import Schema
Schema
.
const Class: <Person>(identifier: string) => <Fields>(fieldsOr: Fields | HasFields<Fields>, annotations?: ClassAnnotations<Person, { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<Fields>]: Schema.Struct.Type<Fields>[K]; }> | undefined) => Schema.Class<Person, Fields, Schema.Struct.Encoded<Fields>, Schema.Schema<in out A, in out I = A, out R = never>.Context<Fields[keyof Fields]>, Schema.Struct.Constructor<Fields>, {}, {}>

@example

import { Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
someField: Schema.String
}) {
someMethod() {
return this.someField + "bar"
}
}

@since3.10.0

Class
<
class Person
Person
>("Person")({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

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

@since3.10.0

String
}) {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
class Person
Person
)({
id: number
id
: 1,
name: string
name
: "name" }))
/*
Output:
Person { id: 1, name: 'name' }
*/
// 模拟基于id异步获取年龄
function
function getAge(id: number): Effect.Effect<number, Error>
getAge
(
id: number
id
: number):
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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

Details

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

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

@since2.0.0

@since2.0.0

Effect
<number,
interface Error
Error
> {
return
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Creates an Effect that always succeeds with a given value.

When to Use

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

Example (Creating a Successful Effect)

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

@seefail to create an effect that represents a failure.

@since2.0.0

succeed
(
id: number
id
+ 2)
}
// 具有转换的扩展类
class
class PersonWithTransform
PersonWithTransform
extends
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof String$; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof String$; }>, never, { ...; } & { ...; }, {}, {}>.transformOrFail<PersonWithTransform>(identifier: string): <NewFields, R2, R3>(fields: NewFields, options: {
readonly decode: (input: {
readonly id: number;
readonly name: string;
}, options: ParseOptions, ast: Transformation) => Effect.Effect<{ [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<{
id: typeof Schema.Number;
name: typeof Schema.String;
} & NewFields>]: Schema.Struct.Type<{
id: typeof Schema.Number;
name: typeof Schema.String;
} & NewFields>[K]; }, ParseResult.ParseIssue, R2>;
readonly encode: (input: { [K in keyof Schema.Struct<Fields extends Schema.Struct.Fields>.Type<{
id: typeof Schema.Number;
name: typeof Schema.String;
} & NewFields>]: Schema.Struct.Type<{
id: typeof Schema.Number;
name: typeof Schema.String;
} & NewFields>[K]; }, options: ParseOptions, ast: Transformation) => Effect.Effect<...>;
}, annotations?: ClassAnnotations<...> | undefined) => Schema.Class<...>

@example

import { Effect, Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
myField: Schema.String
}) {
myMethod() {
return this.myField + "my"
}
}
class NextClass extends MyClass.transformOrFail<NextClass>("NextClass")({
nextField: Schema.Number
}, {
decode: (i) =>
Effect.succeed({
myField: i.myField,
nextField: i.myField.length
}),
encode: (a) => Effect.succeed({ myField: a.myField })
}) {
nextMethod() {
return this.myMethod() + this.myField + this.nextField
}
}

transformOrFail
<
class PersonWithTransform
PersonWithTransform
>(
"PersonWithTransform"
)(
{
age: Schema.optionalWith<typeof Schema.Number, {
exact: true;
as: "Option";
}>
age
:
import Schema
Schema
.
const optionalWith: <typeof Schema.Number, {
exact: true;
as: "Option";
}>(self: typeof Schema.Number, options: {
exact: true;
as: "Option";
}) => Schema.optionalWith<typeof Schema.Number, {
exact: true;
as: "Option";
}> (+1 overload)

@since3.10.0

optionalWith
(
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
, {
exact: true
exact
: true,
as: "Option"
as
: "Option" })
},
{
// 新字段的解码逻辑
decode: (input: {
readonly id: number;
readonly name: string;
}, options: ParseOptions, ast: Transformation) => Effect.Effect<{
readonly id: number;
readonly name: string;
readonly age: Option.Option<number>;
}, ParseResult.ParseIssue, never>
decode
: (
input: {
readonly id: number;
readonly name: string;
}
input
) =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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

Details

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

Example

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

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

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

@since2.0.0

mapBoth
(
function getAge(id: number): Effect.Effect<number, Error>
getAge
(
input: {
readonly id: number;
readonly name: string;
}
input
.
id: number
id
), {
onFailure: (e: Error) => ParseResult.Type
onFailure
: (
e: Error
e
) =>
new
import ParseResult
ParseResult
.
constructor Type(ast: AST, actual: unknown, message?: string | undefined): ParseResult.Type

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

@since3.10.0

Type
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Schema<in out A, in out I = A, out R = never>.ast: AST
ast
,
input: {
readonly id: number;
readonly name: string;
}
input
.
id: number
id
,
e: Error
e
.
Error.message: string
message
),
// 必须返回{ age: Option<number> }
onSuccess: (a: number) => {
age: Option.Option<number>;
id: number;
name: string;
}
onSuccess
: (
age: number
age
) => ({ ...
input: {
readonly id: number;
readonly name: string;
}
input
,
age: Option.Option<number>
age
:
import Option

@since2.0.0

@since2.0.0

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

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

Example (Creating an Option with a Value)

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

@seenone for the opposite operation.

@since2.0.0

some
(
age: number
age
) })
}),
encode: (input: {
readonly id: number;
readonly name: string;
readonly age: Option.Option<number>;
}, options: ParseOptions, ast: Transformation) => Effect.Effect<{
readonly id: number;
} & {
readonly name: string;
}, ParseResult.ParseIssue, never>
encode
:
import ParseResult
ParseResult
.
const succeed: <A>(a: A) => Either<A, ParseResult.ParseIssue>

@since3.10.0

succeed
}
) {}
import Schema
Schema
.
const decodeUnknownPromise: <PersonWithTransform, {
readonly id: number;
readonly name: string;
}>(schema: Schema.Schema<PersonWithTransform, {
readonly id: number;
readonly name: string;
}, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Promise<PersonWithTransform>

@since3.10.0

decodeUnknownPromise
(
class PersonWithTransform
PersonWithTransform
)({
id: number
id
: 1,
name: string
name
: "name"
}).
Promise<PersonWithTransform>.then<void, never>(onfulfilled?: ((value: PersonWithTransform) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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

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

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

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

then
(
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
)
/*
Output:
PersonWithTransform {
id: 1,
name: 'name',
age: { _id: 'Option', _tag: 'Some', value: 3 }
}
*/
// 具有条件转换的扩展类
class
class PersonWithTransformFrom
PersonWithTransformFrom
extends
class Person
Person
.
Class<Person, { id: typeof Number$; name: typeof String$; }, Struct<Fields extends Struct.Fields>.Encoded<{ id: typeof Number$; name: typeof String$; }>, never, { ...; } & { ...; }, {}, {}>.transformOrFailFrom<PersonWithTransformFrom>(identifier: string): <NewFields, R2, R3>(fields: NewFields, options: {
readonly decode: (input: {
readonly id: number;
readonly name: string;
}, options: ParseOptions, ast: Transformation) => Effect.Effect<{ [K in keyof ({
readonly id: number;
readonly name: string;
} & {} & { readonly [K in Exclude<keyof NewFields, Schema.Struct<Fields extends Schema.Struct.Fields>.EncodedOptionalKeys<NewFields>> as Schema.Struct.Key<NewFields, K>]: Schema.Schema<in out A, in out I = A, out R = never>.Encoded<...>; } & { readonly [K in Schema.Struct.EncodedOptionalKeys<...> as Schema.Struct.Key<...>]?: Schema.Schema<in out A, in out I = A, out R = never>.Encoded<...>; })]: ({
readonly id: number;
readonly name: string;
} & ... 2 more ... & { readonly [K in Schema.Struct.EncodedOptionalKeys<...> as Schema.Struct.Key<...>]?: Schema.Schema<in out A, in out I = A, out R = never>.Encoded<...>; })[K]; }, ParseResult.ParseIssue, R2>;
readonly encode: (input: { [K in keyof ({
readonly id: number;
readonly name: string;
} & {} & { readonly [K in Exclude<keyof NewFields, Schema.Struct<Fields extends Schema.Struct.Fields>.EncodedOptionalKeys<NewFields>> as Schema.Struct.Key<NewFields, K>]: Schema.Schema<in out A, in out I = A, out R = never>.Encoded<...>; } & { readonly [K in Schema.Struct.EncodedOptionalKeys<...> as Schema.Struct.Key<...>]?: Schema.Schema<in out A, in out I = A, out R = never>.Encoded<...>; })]: ({
readonly id: number;
readonly name: string;
} & ... 2 more ... & { readonly [K in Schema.Struct.EncodedOptionalKeys<...> as Schema.Struct.Key<...>]?: Schema.Schema<in out A, in out I = A, out R = never>.Encoded<...>; })[K]; }, options: ParseOptions, ast: Transformation) => Effect.Effect<...>;
}, annotations?: ClassAnnotations<...> | undefined) => Schema.Class<...>

@example

import { Effect, Schema } from "effect"
class MyClass extends Schema.Class<MyClass>("MyClass")({
myField: Schema.String
}) {
myMethod() {
return this.myField + "my"
}
}
class NextClass extends MyClass.transformOrFailFrom<NextClass>("NextClass")({
nextField: Schema.Number
}, {
decode: (i) =>
Effect.succeed({
myField: i.myField,
nextField: i.myField.length
}),
encode: (a) => Effect.succeed({ myField: a.myField })
}) {
nextMethod() {
return this.myMethod() + this.myField + this.nextField
}
}

transformOrFailFrom
<
class PersonWithTransformFrom
PersonWithTransformFrom
>(
"PersonWithTransformFrom"
)(
{
age: Schema.optionalWith<typeof Schema.Number, {
exact: true;
as: "Option";
}>
age
:
import Schema
Schema
.
const optionalWith: <typeof Schema.Number, {
exact: true;
as: "Option";
}>(self: typeof Schema.Number, options: {
exact: true;
as: "Option";
}) => Schema.optionalWith<typeof Schema.Number, {
exact: true;
as: "Option";
}> (+1 overload)

@since3.10.0

optionalWith
(
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
, {
exact: true
exact
: true,
as: "Option"
as
: "Option" })
},
{
decode: (input: {
readonly id: number;
readonly name: string;
}, options: ParseOptions, ast: Transformation) => Effect.Effect<{
readonly id: number;
readonly name: string;
readonly age?: number;
}, ParseResult.ParseIssue, never>
decode
: (
input: {
readonly id: number;
readonly name: string;
}
input
) =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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

Details

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

Example

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

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

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

@since2.0.0

mapBoth
(
function getAge(id: number): Effect.Effect<number, Error>
getAge
(
input: {
readonly id: number;
readonly name: string;
}
input
.
id: number
id
), {
onFailure: (e: Error) => ParseResult.Type
onFailure
: (
e: Error
e
) =>
new
import ParseResult
ParseResult
.
constructor Type(ast: AST, actual: unknown, message?: string | undefined): ParseResult.Type

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

@since3.10.0

Type
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Schema<in out A, in out I = A, out R = never>.ast: AST
ast
,
input: {
readonly id: number;
readonly name: string;
}
input
,
e: Error
e
.
Error.message: string
message
),
// 必须返回{ age?: number }
onSuccess: (a: number) => {
age: number;
id: number;
name: string;
} | {
id: number;
name: string;
}
onSuccess
: (
age: number
age
) => (
age: number
age
> 18 ? { ...
input: {
readonly id: number;
readonly name: string;
}
input
,
age: number
age
} : { ...
input: {
readonly id: number;
readonly name: string;
}
input
})
}),
encode: (input: {
readonly id: number;
readonly name: string;
readonly age?: number;
}, options: ParseOptions, ast: Transformation) => Effect.Effect<Schema.Struct.Encoded<{
id: typeof Schema.Number;
name: typeof Schema.String;
}>, ParseResult.ParseIssue, never>
encode
:
import ParseResult
ParseResult
.
const succeed: <A>(a: A) => Either<A, ParseResult.ParseIssue>

@since3.10.0

succeed
}
) {}
import Schema
Schema
.
const decodeUnknownPromise: <PersonWithTransformFrom, {
readonly id: number;
readonly name: string;
}>(schema: Schema.Schema<PersonWithTransformFrom, {
readonly id: number;
readonly name: string;
}, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Promise<PersonWithTransformFrom>

@since3.10.0

decodeUnknownPromise
(
class PersonWithTransformFrom
PersonWithTransformFrom
)({
id: number
id
: 1,
name: string
name
: "name"
}).
Promise<PersonWithTransformFrom>.then<void, never>(onfulfilled?: ((value: PersonWithTransformFrom) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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

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

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

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

then
(
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
)
/*
Output:
PersonWithTransformFrom {
id: 1,
name: 'name',
age: { _id: 'Option', _tag: 'None' }
}
*/

使用哪个API(transformOrFailtransformOrFailFrom)的决定取决于您希望何时执行转换:

  1. 使用transformOrFail

    • 转换在过程结束时发生。
    • 它期望您提供类型为{ age: Option<number> }的值。
    • 在处理初始输入后,新的转换开始发挥作用,您需要确保最终输出符合指定的结构。
  2. 使用transformOrFailFrom

    • 一旦处理初始输入,新的转换就开始。
    • 您应该提供值{ age?: number }
    • 基于这个新输入,后续转换Schema.optionalWith(Schema.Number, { exact: true, as: "Option" })被执行。
    • 这种方法允许立即处理输入,可能影响后续转换。