Skip to content

高级用法

要为原始数据类型(如File)声明模式,您可以使用Schema.declare函数以及类型守卫。

示例(为File声明模式)

import {
import Schema
Schema
} from "effect"
// 使用类型守卫为File类型声明模式
const
const FileFromSelf: Schema.declare<File, File, readonly [], never>
FileFromSelf
=
import Schema
Schema
.
const declare: <File>(is: (input: unknown) => input is File, annotations?: Schema.Annotations.Schema<File, readonly []> | undefined) => Schema.declare<File, File, readonly [], never> (+1 overload)

The constraint R extends Schema.Context<P[number]> enforces dependencies solely from typeParameters. This ensures that when you call Schema.to or Schema.from, you receive a schema with a never context.

@since3.10.0

declare
(
(
input: unknown
input
: unknown):
input: unknown
input
is
interface File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
=>
input: unknown
input
instanceof
var File: typeof File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const FileFromSelf: Schema.declare<File, File, readonly [], never>
FileFromSelf
)
// 解码有效的File对象
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => File
decode
(new
var File: new (sources: Array<BinaryLike | Blob>, fileName: string, options?: FileOptions) => File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
([], "")))
/*
Output:
File { size: 0, type: '', name: '', lastModified: 1724774163056 }
*/
// 解码无效输入
const decode: (u: unknown, overrideOptions?: ParseOptions) => File
decode
(null)
/*
throws
ParseError: Expected <declaration schema>, actual null
*/

要增强默认错误消息,您可以添加注解,特别是identifiertitledescription注解(这些注解都不是必需的,但建议作为良好实践,可以使您的模式”自文档化”)。这些注解将被消息系统利用以返回更有意义的消息。

  • 标识符:模式的唯一名称
  • 标题:简短的描述性标题
  • 描述:模式目的的详细解释

示例(使用注解声明模式)

import {
import Schema
Schema
} from "effect"
// 为File类型声明带有附加注解的模式
const
const FileFromSelf: Schema.declare<File, File, readonly [], never>
FileFromSelf
=
import Schema
Schema
.
const declare: <File>(is: (input: unknown) => input is File, annotations?: Schema.Annotations.Schema<File, readonly []> | undefined) => Schema.declare<File, File, readonly [], never> (+1 overload)

The constraint R extends Schema.Context<P[number]> enforces dependencies solely from typeParameters. This ensures that when you call Schema.to or Schema.from, you receive a schema with a never context.

@since3.10.0

declare
(
(
input: unknown
input
: unknown):
input: unknown
input
is
interface File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
=>
input: unknown
input
instanceof
var File: typeof File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
,
{
// 模式的唯一标识符
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.identifier?: string
identifier
: "FileFromSelf",
// 模式的详细描述
Annotations.Doc<A>.description?: string
description
: "The `File` type in JavaScript"
}
)
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => File
decode
=
import Schema
Schema
.
decodeUnknownSync<File, File>(schema: Schema.Schema<File, File, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => File
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const FileFromSelf: Schema.declare<File, File, readonly [], never>
FileFromSelf
)
// 解码有效的File对象
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => File
decode
(new
var File: new (sources: Array<BinaryLike | Blob>, fileName: string, options?: FileOptions) => File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
([], "")))
/*
Output:
File { size: 0, type: '', name: '', lastModified: 1724774163056 }
*/
// 解码无效输入
const decode: (u: unknown, overrideOptions?: ParseOptions) => File
decode
(null)
/*
throws
ParseError: Expected FileFromSelf, actual null
*/

类型构造器是接受一个或多个类型作为参数并返回新类型的泛型类型。要为类型构造器定义模式,您可以使用Schema.declare函数。

示例(为ReadonlySet<A>声明模式)

import {
import ParseResult
ParseResult
,
import Schema
Schema
} from "effect"
export const
const MyReadonlySet: <A, I, R>(item: Schema.Schema<A, I, R>) => Schema.Schema<ReadonlySet<A>, ReadonlySet<I>, R>
MyReadonlySet
= <
function (type parameter) A in <A, I, R>(item: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlySet<I>, R>
A
,
function (type parameter) I in <A, I, R>(item: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlySet<I>, R>
I
,
function (type parameter) R in <A, I, R>(item: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlySet<I>, R>
R
>(
// Set元素的模式
item: Schema.Schema<A, I, R>
item
:
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never>

@since3.10.0

@since3.10.0

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

@since3.10.0

@since3.10.0

Schema
<
interface ReadonlySet<T>
ReadonlySet
<
function (type parameter) A in <A, I, R>(item: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlySet<I>, R>
A
>,
interface ReadonlySet<T>
ReadonlySet
<
function (type parameter) I in <A, I, R>(item: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlySet<I>, R>
I
>,
function (type parameter) R in <A, I, R>(item: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlySet<I>, R>
R
> =>
import Schema
Schema
.
const declare: <ReadonlySet<A>, ReadonlySet<I>, readonly [Schema.Schema<A, I, R>]>(typeParameters: readonly [Schema.Schema<A, I, R>], options: {
readonly decode: (typeParameters_0: Schema.Schema<A, I, never>) => (input: unknown, options: ParseOptions, ast: Declaration) => Effect<ReadonlySet<A>, ParseResult.ParseIssue, never>;
readonly encode: (typeParameters_0: Schema.Schema<A, I, never>) => (input: unknown, options: ParseOptions, ast: Declaration) => Effect<...>;
}, annotations?: Schema.Annotations.Schema<...> | undefined) => Schema.declare<...> (+1 overload)

The constraint R extends Schema.Context<P[number]> enforces dependencies solely from typeParameters. This ensures that when you call Schema.to or Schema.from, you receive a schema with a never context.

@since3.10.0

declare
(
// 存储Set元素的模式
[
item: Schema.Schema<A, I, R>
item
],
{
// 解码函数
decode: (typeParameters_0: Schema.Schema<A, I, never>) => (input: unknown, options: ParseOptions, ast: Declaration) => Effect<ReadonlySet<A>, ParseResult.ParseIssue, never>
decode
: (
item: Schema.Schema<A, I, never>
item
) => (
input: unknown
input
,
parseOptions: ParseOptions
parseOptions
,
ast: Declaration
ast
) => {
if (
input: unknown
input
instanceof
var Set: SetConstructor
Set
) {
// 解码Set中的每个元素
const
const elements: Effect<readonly A[], ParseResult.ParseIssue, never>
elements
=
import ParseResult
ParseResult
.
const decodeUnknown: <readonly A[], readonly I[], never>(schema: Schema.Schema<readonly A[], readonly I[], never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Effect<readonly A[], ParseResult.ParseIssue, never>

@since3.10.0

decodeUnknown
(
import Schema
Schema
.
Array<Schema.Schema<A, I, never>>(value: Schema.Schema<A, I, never>): Schema.Array$<Schema.Schema<A, I, never>>
export Array

@since3.10.0

Array
(
item: Schema.Schema<A, I, never>
item
))(
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<any>(iterable: Iterable<any> | ArrayLike<any>): any[] (+3 overloads)

Creates an array from an iterable object.

@paramiterable An iterable object to convert to an array.

from
(
input: Set<any>
input
.
Set<any>.values(): SetIterator<any>

Returns an iterable of values in the set.

values
()),
parseOptions: ParseOptions
parseOptions
)
// 返回包含解码元素的ReadonlySet
return
import ParseResult
ParseResult
.
const map: <readonly A[], ParseResult.ParseIssue, never, ReadonlySet<A>>(self: Effect<readonly A[], ParseResult.ParseIssue, never>, f: (a: readonly A[]) => ReadonlySet<A>) => Effect<ReadonlySet<A>, ParseResult.ParseIssue, never> (+1 overload)

@since3.10.0

map
(
const elements: Effect<readonly A[], ParseResult.ParseIssue, never>
elements
,
(
as: readonly A[]
as
):
interface ReadonlySet<T>
ReadonlySet
<
function (type parameter) A in <A, I, R>(item: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlySet<I>, R>
A
> => new
var Set: SetConstructor
new <A>(iterable?: Iterable<A> | null | undefined) => Set<A> (+1 overload)
Set
(
as: readonly A[]
as
)
)
}
// 处理无效输入
return
import ParseResult
ParseResult
.
const fail: (issue: ParseResult.ParseIssue) => Either<never, ParseResult.ParseIssue>

@since3.10.0

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

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

@since3.10.0

Type
(
ast: Declaration
ast
,
input: unknown
input
))
},
// 编码函数
encode: (typeParameters_0: Schema.Schema<A, I, never>) => (input: unknown, options: ParseOptions, ast: Declaration) => Effect<ReadonlySet<I>, ParseResult.ParseIssue, never>
encode
: (
item: Schema.Schema<A, I, never>
item
) => (
input: unknown
input
,
parseOptions: ParseOptions
parseOptions
,
ast: Declaration
ast
) => {
if (
input: unknown
input
instanceof
var Set: SetConstructor
Set
) {
// 编码Set中的每个元素
const
const elements: Effect<readonly I[], ParseResult.ParseIssue, never>
elements
=
import ParseResult
ParseResult
.
const encodeUnknown: <readonly A[], readonly I[], never>(schema: Schema.Schema<readonly A[], readonly I[], never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Effect<readonly I[], ParseResult.ParseIssue, never>

@since3.10.0

encodeUnknown
(
import Schema
Schema
.
Array<Schema.Schema<A, I, never>>(value: Schema.Schema<A, I, never>): Schema.Array$<Schema.Schema<A, I, never>>
export Array

@since3.10.0

Array
(
item: Schema.Schema<A, I, never>
item
))(
var Array: ArrayConstructor
Array
.
ArrayConstructor.from<any>(iterable: Iterable<any> | ArrayLike<any>): any[] (+3 overloads)

Creates an array from an iterable object.

@paramiterable An iterable object to convert to an array.

from
(
input: Set<any>
input
.
Set<any>.values(): SetIterator<any>

Returns an iterable of values in the set.

values
()),
parseOptions: ParseOptions
parseOptions
)
// 返回包含编码元素的ReadonlySet
return
import ParseResult
ParseResult
.
const map: <readonly I[], ParseResult.ParseIssue, never, ReadonlySet<I>>(self: Effect<readonly I[], ParseResult.ParseIssue, never>, f: (a: readonly I[]) => ReadonlySet<I>) => Effect<ReadonlySet<I>, ParseResult.ParseIssue, never> (+1 overload)

@since3.10.0

map
(
const elements: Effect<readonly I[], ParseResult.ParseIssue, never>
elements
,
(
is: readonly I[]
is
):
interface ReadonlySet<T>
ReadonlySet
<
function (type parameter) I in <A, I, R>(item: Schema.Schema<A, I, R>): Schema.Schema<ReadonlySet<A>, ReadonlySet<I>, R>
I
> => new
var Set: SetConstructor
new <I>(iterable?: Iterable<I> | null | undefined) => Set<I> (+1 overload)
Set
(
is: readonly I[]
is
)
)
}
// 处理无效输入
return
import ParseResult
ParseResult
.
const fail: (issue: ParseResult.ParseIssue) => Either<never, ParseResult.ParseIssue>

@since3.10.0

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

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

@since3.10.0

Type
(
ast: Declaration
ast
,
input: unknown
input
))
}
},
{
Annotations.Doc<A>.description?: string
description
: `ReadonlySet<${
import Schema
Schema
.
const format: <Schema.Schema<A, I, R>>(schema: Schema.Schema<A, I, R>) => string

@since3.10.0

format
(
item: Schema.Schema<A, I, R>
item
)}>`
}
)
// 为数字的ReadonlySet定义模式
const
const setOfNumbers: Schema.Schema<ReadonlySet<number>, ReadonlySet<string>, never>
setOfNumbers
=
const MyReadonlySet: <number, string, never>(item: Schema.Schema<number, string, never>) => Schema.Schema<ReadonlySet<number>, ReadonlySet<string>, never>
MyReadonlySet
(
import Schema
Schema
.
class NumberFromString

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

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

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

@since3.10.0

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const setOfNumbers: Schema.Schema<ReadonlySet<number>, ReadonlySet<string>, never>
setOfNumbers
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => ReadonlySet<number>
decode
(new
var Set: SetConstructor
new <string>(iterable?: Iterable<string> | null | undefined) => Set<string> (+1 overload)
Set
(["1", "2", "3"]))) // Set(3) { 1, 2, 3 }
// 解码无效输入
const decode: (u: unknown, overrideOptions?: ParseOptions) => ReadonlySet<number>
decode
(null)
/*
throws
ParseError: Expected ReadonlySet<NumberFromString>, actual null
*/
// 解码包含无效元素的Set
const decode: (u: unknown, overrideOptions?: ParseOptions) => ReadonlySet<number>
decode
(new
var Set: SetConstructor
new <string | null>(iterable?: Iterable<string | null> | null | undefined) => Set<string | null> (+1 overload)
Set
(["1", null, "3"]))
/*
throws
ParseError: ReadonlyArray<NumberFromString>
└─ [1]
└─ NumberFromString
└─ Encoded side transformation failure
└─ Expected string, actual null
*/

在定义新数据类型时,一些编译器如ArbitraryPretty可能不知道如何处理新类型。 这可能导致错误,因为编译器可能缺乏生成实例或产生可读输出的必要信息:

示例(尝试在没有必需注解的情况下生成任意值)

import {
import Arbitrary
Arbitrary
,
import Schema
Schema
} from "effect"
// 为File类型定义模式
const
const FileFromSelf: Schema.declare<File, File, readonly [], never>
FileFromSelf
=
import Schema
Schema
.
const declare: <File>(is: (input: unknown) => input is File, annotations?: Schema.Annotations.Schema<File, readonly []> | undefined) => Schema.declare<File, File, readonly [], never> (+1 overload)

The constraint R extends Schema.Context<P[number]> enforces dependencies solely from typeParameters. This ensures that when you call Schema.to or Schema.from, you receive a schema with a never context.

@since3.10.0

declare
(
(
input: unknown
input
: unknown):
input: unknown
input
is
interface File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
=>
input: unknown
input
instanceof
var File: typeof File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
,
{
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.identifier?: string
identifier
: "FileFromSelf"
}
)
// 尝试为模式创建Arbitrary实例
const
const arb: Arbitrary<File>
arb
=
import Arbitrary
Arbitrary
.
const make: <File, File, never>(schema: Schema.Schema<File, File, never>) => Arbitrary<File>

Returns a fast-check Arbitrary for the A type of the provided schema.

@since3.10.0

make
(
const FileFromSelf: Schema.declare<File, File, readonly [], never>
FileFromSelf
)
/*
throws:
Error: Missing annotation
details: Generating an Arbitrary for this schema requires an "arbitrary" annotation
schema (Declaration): FileFromSelf
*/

在上面的示例中,尝试为FileFromSelf模式生成任意值失败,因为编译器缺乏必要的注解。要解决这个问题,您需要提供用于生成任意数据的注解:

示例(为自定义File模式添加Arbitrary注解)

import {
import Arbitrary
Arbitrary
,
import FastCheck
FastCheck
,
import Pretty
Pretty
,
import Schema
Schema
} from "effect"
const
const FileFromSelf: Schema.declare<File, File, readonly [], never>
FileFromSelf
=
import Schema
Schema
.
const declare: <File>(is: (input: unknown) => input is File, annotations?: Schema.Annotations.Schema<File, readonly []> | undefined) => Schema.declare<File, File, readonly [], never> (+1 overload)

The constraint R extends Schema.Context<P[number]> enforces dependencies solely from typeParameters. This ensures that when you call Schema.to or Schema.from, you receive a schema with a never context.

@since3.10.0

declare
(
(
input: unknown
input
: unknown):
input: unknown
input
is
interface File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
=>
input: unknown
input
instanceof
var File: typeof File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
,
{
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.identifier?: string
identifier
: "FileFromSelf",
// 提供一个生成随机File实例的函数
Annotations.Schema<File, readonly []>.arbitrary?: Arbitrary.ArbitraryAnnotation<File, readonly []>
arbitrary
: () => (
fc: typeof FastCheck
fc
) =>
fc: typeof FastCheck
fc
.
tuple<[string, string]>(arbs_0: FastCheck.Arbitrary<string>, arbs_1: FastCheck.Arbitrary<string>): FastCheck.Arbitrary<[string, string]>
export tuple

For tuples produced using the provided arbs

@paramarbs - Ordered list of arbitraries

@public

tuple
(
fc: typeof FastCheck
fc
.
function string(constraints?: FastCheck.StringConstraints): FastCheck.Arbitrary<string>
export string

For strings of

char

@paramconstraints - Constraints to apply when building instances (since 2.4.0)

@public

string
(),
fc: typeof FastCheck
fc
.
function string(constraints?: FastCheck.StringConstraints): FastCheck.Arbitrary<string>
export string

For strings of

char

@paramconstraints - Constraints to apply when building instances (since 2.4.0)

@public

string
())
.
Arbitrary<[string, string]>.map<File>(mapper: (t: [string, string]) => File, unmapper?: ((possiblyU: unknown) => [string, string]) | undefined): FastCheck.Arbitrary<File>

Create another arbitrary by mapping all produced values using the provided mapper Values produced by the new arbitrary are the result of applying mapper value by value

@example

const rgbChannels: Arbitrary<{r:number,g:number,b:number}> = ...;
const color: Arbitrary<string> = rgbChannels.map(ch => `#${(ch.r*65536 + ch.g*256 + ch.b).toString(16).padStart(6, '0')}`);
// transform an Arbitrary producing {r,g,b} integers into an Arbitrary of '#rrggbb'

@parammapper - Map function, to produce a new element based on an old one

@paramunmapper - Optional unmap function, it will never be used except when shrinking user defined values. Must throw if value is not compatible (since 3.0.0)

@returnsNew arbitrary with mapped elements

map
(([
content: string
content
,
path: string
path
]) => new
var File: new (sources: Array<BinaryLike | Blob>, fileName: string, options?: FileOptions) => File

File class is a global reference for import { File } from 'node:buffer' https://nodejs.org/api/buffer.html#class-file

@sincev20.0.0

File
([
content: string
content
],
path: string
path
))
}
)
// 为模式创建Arbitrary实例
const
const arb: FastCheck.Arbitrary<File>
arb
=
import Arbitrary
Arbitrary
.
const make: <File, File, never>(schema: Schema.Schema<File, File, never>) => FastCheck.Arbitrary<File>

Returns a fast-check Arbitrary for the A type of the provided schema.

@since3.10.0

make
(
const FileFromSelf: Schema.declare<File, File, readonly [], never>
FileFromSelf
)
// 使用Arbitrary实例生成示例文件
const
const files: File[]
files
=
import FastCheck
FastCheck
.
sample<File>(generator: FastCheck.Arbitrary<File> | FastCheck.IRawProperty<File, boolean>, params?: number | FastCheck.Parameters<File> | undefined): File[]
export sample

Generate an array containing all the values that would have been generated during

assert

or

check

@example

fc.sample(fc.nat(), 10); // extract 10 values from fc.nat() Arbitrary
fc.sample(fc.nat(), {seed: 42}); // extract values from fc.nat() as if we were running fc.assert with seed=42

@paramgenerator - IProperty or Arbitrary to extract the values from

@paramparams - Integer representing the number of values to generate or Parameters as in assert

@public

sample
(
const arb: FastCheck.Arbitrary<File>
arb
, 2)
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 files: File[]
files
)
/*
Example Output:
[
File { size: 5, type: '', name: 'C', lastModified: 1706435571176 },
File { size: 1, type: '', name: '98Ggmc', lastModified: 1706435571176 }
]
*/

有关如何为Arbitrary编译器添加注解的更多详细信息,请参阅Arbitrary文档。

TypeScript的类型系统是结构化的,这意味着任何两个结构等价的类型都被认为是相同的。 当语义上不同的类型被当作相同类型处理时,这可能会导致问题。

示例(结构化类型问题)

type
type UserId = string
UserId
= string
type
type Username = string
Username
= string
declare const
const getUser: (id: UserId) => object
getUser
: (
id: string
id
:
type UserId = string
UserId
) => object
const
const myUsername: string
myUsername
:
type Username = string
Username
= "gcanti"
const getUser: (id: UserId) => object
getUser
(
const myUsername: string
myUsername
) // 这错误地工作了

在上面的示例中,UserIdUsername都是同一类型string的别名。这意味着getUser函数可能错误地接受Username作为有效的UserId,导致错误和问题。

为了防止这种情况,Effect引入了品牌类型。这些类型将唯一标识符(或”品牌”)附加到类型上,允许您区分结构相似但语义不同的类型。

示例(定义品牌类型)

import {
import Brand
Brand
} from "effect"
type
type UserId = string & Brand.Brand<"UserId">
UserId
= string &
import Brand
Brand
.
interface Brand<in out K extends string | symbol>

A generic interface that defines a branded type.

@since2.0.0

@since2.0.0

Brand
<"UserId">
type
type Username = string
Username
= string
declare const
const getUser: (id: UserId) => object
getUser
: (
id: UserId
id
:
type UserId = string & Brand.Brand<"UserId">
UserId
) => object
const
const myUsername: string
myUsername
:
type Username = string
Username
= "gcanti"
const getUser: (id: UserId) => object
getUser
(myUsername)
Error ts(2345) ― Argument of type 'string' is not assignable to parameter of type 'UserId'. Type 'string' is not assignable to type 'Brand<"UserId">'.

通过将UserId定义为品牌类型,getUser函数只能接受UserId类型的值,而不能接受普通字符串或其他与字符串兼容的类型。这有助于防止因意外传递错误类型的值给函数而导致的错误。

有两种方式为品牌类型定义模式,取决于您是否:

  • 想要从头开始定义模式
  • 已经通过effect/Brand定义了品牌类型并想要重用它来定义模式

要从头开始为品牌类型定义模式,请使用Schema.brand函数。

示例(为品牌类型创建模式)

import {
import Schema
Schema
} from "effect"
const
const UserId: Schema.brand<typeof Schema.String, "UserId">
UserId
=
import Schema
Schema
.
class String
export String

@since3.10.0

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

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

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

@example

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

@since3.10.0

brand
("UserId"))
// string & Brand<"UserId">
type
type UserId = string & Brand<"UserId">
UserId
= typeof
const UserId: Schema.brand<typeof Schema.String, "UserId">
UserId
.
Schema<string & Brand<"UserId">, string, never>.Type: string & Brand<"UserId">
Type

请注意,您可以使用unique symbol作为品牌来确保跨模块/包的唯一性。

示例(使用唯一符号作为品牌)

import {
import Schema
Schema
} from "effect"
const
const UserIdBrand: typeof UserIdBrand
UserIdBrand
: unique symbol =
var Symbol: SymbolConstructor
Symbol
.
SymbolConstructor.for(key: string): symbol

Returns a Symbol object from the global symbol registry matching the given key if found. Otherwise, returns a new symbol with this key.

@paramkey key to search for.

for
("UserId")
const
const UserId: Schema.brand<typeof Schema.String, typeof UserIdBrand>
UserId
=
import Schema
Schema
.
class String
export String

@since3.10.0

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

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

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

@example

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

@since3.10.0

brand
(
const UserIdBrand: typeof UserIdBrand
UserIdBrand
))
// string & Brand<typeof UserIdBrand>
type
type UserId = string & Brand<typeof UserIdBrand>
UserId
= typeof
const UserId: Schema.brand<typeof Schema.String, typeof UserIdBrand>
UserId
.
Schema<string & Brand<typeof UserIdBrand>, string, never>.Type: string & Brand<typeof UserIdBrand>
Type

如果您已经使用effect/Brand模块定义了品牌类型,您可以使用Schema.fromBrand函数重用它来定义模式。

示例(重用现有的品牌类型)

import {
import Schema
Schema
} from "effect"
import {
import Brand
Brand
} from "effect"
// 现有的品牌类型
type
type UserId = string & Brand.Brand<"UserId">
UserId
= string &
import Brand
Brand
.
interface Brand<in out K extends string | symbol>

A generic interface that defines a branded type.

@since2.0.0

@since2.0.0

Brand
<"UserId">
const
const UserId: Brand.Brand.Constructor<UserId>
UserId
=
import Brand
Brand
.
const nominal: <UserId>() => Brand.Brand<in out K extends string | symbol>.Constructor<UserId>

This function returns a Brand.Constructor that does not apply any runtime checks, it just returns the provided value. It can be used to create nominal types that allow distinguishing between two values of the same type but with different meanings.

If you also want to perform some validation, see

refined

.

Example

import * as assert from "node:assert"
import { Brand } from "effect"
type UserId = number & Brand.Brand<"UserId">
const UserId = Brand.nominal<UserId>()
console.log(UserId(1))
// 1

@since2.0.0

nominal
<
type UserId = string & Brand.Brand<"UserId">
UserId
>()
// 为品牌类型定义模式
const
const UserIdSchema: Schema.BrandSchema<string & Brand.Brand<"UserId">, string, never>
UserIdSchema
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.BrandSchema<string & Brand.Brand<"UserId">, string, never>>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.BrandSchema<string & Brand.Brand<"UserId">, string, never>): Schema.BrandSchema<string & Brand.Brand<"UserId">, string, never> (+21 overloads)
pipe
(
import Schema
Schema
.
const fromBrand: <UserId, string>(constructor: Brand.Brand<in out K extends string | symbol>.Constructor<UserId>, annotations?: Schema.Annotations.Filter<UserId, string> | undefined) => <I, R>(self: Schema.Schema<string, I, R>) => Schema.BrandSchema<string & Brand.Brand<"UserId">, I, R>

@since3.10.0

fromBrand
(
const UserId: Brand.Brand.Constructor<UserId>
UserId
))

Schema.brand函数包含一个默认构造器来便于创建品牌值。

import {
import Schema
Schema
} from "effect"
const
const UserId: Schema.brand<typeof Schema.String, "UserId">
UserId
=
import Schema
Schema
.
class String
export String

@since3.10.0

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

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

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

@example

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

@since3.10.0

brand
("UserId"))
const
const userId: string & Brand<"UserId">
userId
=
const UserId: Schema.brand<typeof Schema.String, "UserId">
UserId
.
BrandSchema<string & Brand<"UserId">, string, never>.make(a: string, options?: Schema.MakeOptions): string & Brand<"UserId">
make
("123") // 创建一个品牌UserId

PropertySignature表示从”From”字段到”To”字段的转换。这允许您定义传入数据字段与内部模型之间的映射。

属性签名可以使用注解定义,以提供关于字段的额外上下文。

示例(为属性签名添加注解)

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

@since3.10.0

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

@since3.10.0

String
,
age: Schema.propertySignature<typeof Schema.NumberFromString>
age
:
import Schema
Schema
.
const propertySignature: <typeof Schema.NumberFromString>(self: typeof Schema.NumberFromString) => Schema.propertySignature<typeof Schema.NumberFromString>

Lifts a Schema into a PropertySignature.

@since3.10.0

propertySignature
(
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
).
propertySignature<typeof NumberFromString>.annotations(annotations: Schema.PropertySignature<TypeToken extends Schema.PropertySignature.Token, Type, Key extends PropertyKey, EncodedToken extends Schema.PropertySignature.Token, Encoded, HasDefault extends boolean = false, R = never>.Annotations<number>): Schema.propertySignature<typeof Schema.NumberFromString>
annotations
({
Annotations.Doc<number>.title?: string
title
: "Age" // 标记age字段的注解
})
})

A PropertySignature type contains several parameters, each providing details about the transformation between the source field (From) and the target field (To). Let’s take a look at what each of these parameters represents:

age: PropertySignature<
ToToken,
ToType,
FromKey,
FromToken,
FromType,
HasDefault,
Context
>
ParameterDescription
ageKey of the “To” field
ToTokenIndicates field requirement: "?:" for optional, ":" for required
ToTypeType of the “To” field
FromKey(Optional, default = never) Indicates the source field key, typically the same as “To” field key unless specified
FromTokenIndicates source field requirement: "?:" for optional, ":" for required
FromTypeType of the “From” field
HasDefaultIndicates if there is a constructor default value (Boolean)

In the example above, the PropertySignature type for age is:

PropertySignature<":", number, never, ":", string, false, never>

This means:

参数描述
age”To”字段的键
ToToken":"表示age字段是必需的
ToTypeage字段的类型是number
FromKeynever表示解码发生在同名的age字段
FromToken":"表示解码发生在必需的age字段
FromType”From”字段的类型是string
HasDefaultfalse:表示没有默认值

有时,源字段(“From”字段)可能与内部模型中的字段名称不同。您可以使用Schema.fromKey函数在这些字段之间进行映射。

示例(从不同键映射)

import {
import Schema
Schema
} from "effect"
const
const Person: Schema.Struct<{
name: typeof Schema.String;
age: Schema.PropertySignature<":", number, "AGE", ":", string, false, never>;
}>
Person
=
import Schema
Schema
.
function Struct<{
name: typeof Schema.String;
age: Schema.PropertySignature<":", number, "AGE", ":", string, false, never>;
}>(fields: {
name: typeof Schema.String;
age: Schema.PropertySignature<":", number, "AGE", ":", string, false, never>;
}): Schema.Struct<{
name: typeof Schema.String;
age: Schema.PropertySignature<":", number, "AGE", ":", string, false, never>;
}> (+1 overload)

@since3.10.0

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

@since3.10.0

String
,
age: Schema.PropertySignature<":", number, "AGE", ":", string, false, never>
age
:
import Schema
Schema
.
const propertySignature: <typeof Schema.NumberFromString>(self: typeof Schema.NumberFromString) => Schema.propertySignature<typeof Schema.NumberFromString>

Lifts a Schema into a PropertySignature.

@since3.10.0

propertySignature
(
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.propertySignature<typeof Schema.NumberFromString>, Schema.PropertySignature<":", number, "AGE", ":", string, false, never>>(this: Schema.propertySignature<typeof Schema.NumberFromString>, ab: (_: Schema.propertySignature<typeof Schema.NumberFromString>) => Schema.PropertySignature<":", number, "AGE", ":", string, false, never>): Schema.PropertySignature<":", number, "AGE", ":", string, false, never> (+21 overloads)
pipe
(
import Schema
Schema
.
const fromKey: <"AGE">(key: "AGE") => <TypeToken, Type, EncodedToken, Encoded, HasDefault, R>(self: Schema.PropertySignature<TypeToken, Type, PropertyKey, EncodedToken, Encoded, HasDefault, R>) => Schema.PropertySignature<TypeToken, Type, "AGE", EncodedToken, Encoded, HasDefault, R> (+1 overload)

Enhances a property signature by specifying a different key for it in the Encoded type.

@since3.10.0

fromKey
("AGE") // 从"AGE"映射到"age"
)
})
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Person: Schema.Struct<{
name: typeof Schema.String;
age: Schema.PropertySignature<":", number, "AGE", ":", string, false, never>;
}>
Person
)({
name: string
name
: "name",
type AGE: string
AGE
: "18" }))
// Output: { name: 'name', age: 18 }

当您从"AGE"映射到"age"时,PropertySignature类型变为:

PropertySignature<":", number, never, ":", string, false, never>
PropertySignature<":", number, "AGE", ":", string, false, never>

语法:

Schema.optional(schema: Schema<A, I, R>)

在模式中创建可选属性,允许字段被省略或设置为undefined

输入输出
<缺失值>保持<缺失值>
undefined保持undefined
i: I转换为a: A
输入输出
<缺失值>保持<缺失值>
undefined保持undefined
a: A转换回i: I

示例(定义可选数字字段)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>(fields: {
quantity: Schema.optional<typeof Schema.NumberFromString>;
}): Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optional<typeof Schema.NumberFromString>
quantity
:
import Schema
Schema
.
const optional: <typeof Schema.NumberFromString>(self: typeof Schema.NumberFromString) => Schema.optional<typeof Schema.NumberFromString>

@since3.10.0

optional
(
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
)
})
// ┌─── { readonly quantity?: string | undefined; }
// ▼
type
type Encoded = {
readonly quantity?: string | undefined;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
.
Schema<{ readonly quantity?: number | undefined; }, { readonly quantity?: string | undefined; }, never>.Encoded: {
readonly quantity?: string | undefined;
}
Encoded
// ┌─── { readonly quantity?: number | undefined; }
// ▼
type
type Type = {
readonly quantity?: number | undefined;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
.
Schema<{ readonly quantity?: number | undefined; }, { readonly quantity?: string | undefined; }, never>.Type: {
readonly quantity?: number | undefined;
}
Type
// 解码示例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
)({
quantity: string
quantity
: "1" }))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
)({}))
// Output: {}
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<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity?: number | undefined;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
// Output: { quantity: undefined }
// 编码示例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | undefined;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number | undefined;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string | undefined;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
)({
quantity?: number | undefined
quantity
: 1 }))
// Output: { quantity: "1" }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | undefined;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number | undefined;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string | undefined;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
)({}))
// Output: {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | undefined;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number | undefined;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string | undefined;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
)({
quantity?: number | undefined
quantity
:
var undefined
undefined
}))
// Output: { quantity: undefined }

您可以使用from属性访问原始模式类型(在标记为可选之前)。

示例(访问原始模式)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>(fields: {
quantity: Schema.optional<typeof Schema.NumberFromString>;
}): Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optional<typeof Schema.NumberFromString>
quantity
:
import Schema
Schema
.
const optional: <typeof Schema.NumberFromString>(self: typeof Schema.NumberFromString) => Schema.optional<typeof Schema.NumberFromString>

@since3.10.0

optional
(
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
)
})
// ┌─── typeof Schema.NumberFromString
// ▼
const
const from: typeof Schema.NumberFromString
from
=
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
Product
.
Struct<{ quantity: optional<typeof NumberFromString>; }>.fields: Readonly<{
quantity: Schema.optional<typeof Schema.NumberFromString>;
}>
fields
.
quantity: Schema.optional<typeof Schema.NumberFromString>
quantity
.
optional<typeof NumberFromString>.from: typeof Schema.NumberFromString
from

语法:

Schema.optionalWith(schema: Schema<A, I, R>, { nullable: true })

在模式中创建可选属性,将null值视为与缺失值相同。

输入输出
<缺失值>保持<缺失值>
undefined保持undefined
null转换为<缺失值>
i: I转换为a: A
输入输出
<缺失值>保持<缺失值>
undefined保持undefined
a: A转换回i: I

示例(将Null处理为缺失值)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
nullable: true
nullable
: true
})
})
// ┌─── { readonly quantity?: string | null | undefined; }
// ▼
type
type Encoded = {
readonly quantity?: string | null | undefined;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity?: number | undefined; }, { readonly quantity?: string | null | undefined; }, never>.Encoded: {
readonly quantity?: string | null | undefined;
}
Encoded
// ┌─── { readonly quantity?: number | undefined; }
// ▼
type
type Type = {
readonly quantity?: number | undefined;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity?: number | undefined; }, { readonly quantity?: string | null | undefined; }, never>.Type: {
readonly quantity?: number | undefined;
}
Type
// 解码示例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity?: number | undefined;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
)({
quantity: string
quantity
: "1" }))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity?: number | undefined;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
)({}))
// Output: {}
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<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity?: number | undefined;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
// Output: { quantity: undefined }
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<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity?: number | undefined;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
)({
quantity: null
quantity
: null }))
// Output: {}
// 编码示例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number | undefined;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string | null | undefined;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
)({
quantity?: number | undefined
quantity
: 1 }))
// Output: { quantity: "1" }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number | undefined;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string | null | undefined;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
)({}))
// Output: {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity?: number | undefined;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number | undefined;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string | null | undefined;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
)({
quantity?: number | undefined
quantity
:
var undefined
undefined
}))
// Output: { quantity: undefined }

您可以使用from属性访问原始模式类型(在标记为可选之前)。

示例(访问原始模式)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
nullable: true
nullable
: true
})
})
// ┌─── typeof Schema.NumberFromString
// ▼
const
const from: typeof Schema.NumberFromString
from
=
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { nullable: true; }>; }>.fields: Readonly<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>;
}>
fields
.
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
nullable: true;
}>
quantity
.
optionalWith<typeof NumberFromString, { nullable: true; }>.from: typeof Schema.NumberFromString
from

语法:

Schema.optionalWith(schema: Schema<A, I, R>, { exact: true })

创建可选属性的同时强制严格类型。这意味着只接受指定的类型(不包括undefined)。任何尝试解码undefined的操作都会导致错误。

输入输出
<缺失值>保持<缺失值>
undefinedParseError
i: I转换为a: A
输入输出
<缺失值>保持<缺失值>
a: A转换回i: I

示例(在可选字段中使用精确性)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
exact: true;
}>(self: typeof Schema.NumberFromString, options: {
exact: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
exact: true
exact
: true })
})
// ┌─── { readonly quantity?: string; }
// ▼
type
type Encoded = {
readonly quantity?: string;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
.
Schema<{ readonly quantity?: number; }, { readonly quantity?: string; }, never>.Encoded: {
readonly quantity?: string;
}
Encoded
// ┌─── { readonly quantity?: number; }
// ▼
type
type Type = {
readonly quantity?: number;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
.
Schema<{ readonly quantity?: number; }, { readonly quantity?: string; }, never>.Type: {
readonly quantity?: number;
}
Type
// 解码示例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
)({
quantity: string
quantity
: "1" }))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
)({}))
// Output: {}
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<{
readonly quantity?: number;
}, {
readonly quantity?: string;
}>(schema: Schema.Schema<{
readonly quantity?: number;
}, {
readonly quantity?: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity?: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
/*
throws:
ParseError: { readonly quantity?: NumberFromString }
└─ ["quantity"]
└─ NumberFromString
└─ Encoded side transformation failure
└─ Expected string, actual undefined
*/
// 编码示例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number;
}, {
readonly quantity?: string;
}>(schema: Schema.Schema<{
readonly quantity?: number;
}, {
readonly quantity?: string;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
)({
quantity?: number
quantity
: 1 }))
// Output: { quantity: "1" }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number;
}, {
readonly quantity?: string;
}>(schema: Schema.Schema<{
readonly quantity?: number;
}, {
readonly quantity?: string;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
)({}))
// Output: {}

您可以使用from属性访问原始模式类型(在标记为可选之前)。

示例(访问原始模式)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
exact: true;
}>(self: typeof Schema.NumberFromString, options: {
exact: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
exact: true
exact
: true })
})
// ┌─── typeof Schema.NumberFromString
// ▼
const
const from: typeof Schema.NumberFromString
from
=
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { exact: true; }>; }>.fields: Readonly<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>;
}>
fields
.
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
}>
quantity
.
optionalWith<typeof NumberFromString, { exact: true; }>.from: typeof Schema.NumberFromString
from

语法:

Schema.optionalWith(schema: Schema<A, I, R>, { exact: true, nullable: true })

允许您定义一个可选属性,该属性强制严格类型(仅精确类型),同时将null视为等同于缺失值。

输入输出
<缺失值>保持<缺失值>
null转换为<缺失值>
undefinedParseError
i: I转换为a: A
输入输出
<缺失值>保持<缺失值>
a: A转换回i: I

示例(在可选字段中使用精确性并将Null处理为缺失值)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
exact: true;
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
exact: true
exact
: true,
nullable: true
nullable
: true
})
})
// ┌─── { readonly quantity?: string | null; }
// ▼
type
type Encoded = {
readonly quantity?: string | null;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity?: number; }, { readonly quantity?: string | null; }, never>.Encoded: {
readonly quantity?: string | null;
}
Encoded
// ┌─── { readonly quantity?: number; }
// ▼
type
type Type = {
readonly quantity?: number;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity?: number; }, { readonly quantity?: string | null; }, never>.Type: {
readonly quantity?: number;
}
Type
// 解码示例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity: string
quantity
: "1" }))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
)({}))
// Output: {}
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<{
readonly quantity?: number;
}, {
readonly quantity?: string | null;
}>(schema: Schema.Schema<{
readonly quantity?: number;
}, {
readonly quantity?: string | null;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity?: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
/*
throws:
ParseError: (Struct (Encoded side) <-> Struct (Type side))
└─ Encoded side transformation failure
└─ Struct (Encoded side)
└─ ["quantity"]
└─ NumberFromString | null
├─ NumberFromString
│ └─ Encoded side transformation failure
│ └─ Expected string, actual undefined
└─ Expected null, actual undefined
*/
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<{
readonly quantity?: number;
}, {
readonly quantity?: string | null;
}>(schema: Schema.Schema<{
readonly quantity?: number;
}, {
readonly quantity?: string | null;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity?: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity: null
quantity
: null }))
// Output: {}
// 编码示例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number;
}, {
readonly quantity?: string | null;
}>(schema: Schema.Schema<{
readonly quantity?: number;
}, {
readonly quantity?: string | null;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string | null;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity?: number
quantity
: 1 }))
// Output: { quantity: "1" }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
encodeSync<{
readonly quantity?: number;
}, {
readonly quantity?: string | null;
}>(schema: Schema.Schema<{
readonly quantity?: number;
}, {
readonly quantity?: string | null;
}, never>, options?: ParseOptions): (a: {
readonly quantity?: number;
}, overrideOptions?: ParseOptions) => {
readonly quantity?: string | null;
}
export encodeSync

@since3.10.0

encodeSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
)({}))
// Output: {}

您可以使用from属性访问原始模式类型(在标记为可选之前)。

示例(访问原始模式)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
exact: true;
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
exact: true
exact
: true,
nullable: true
nullable
: true
})
})
// ┌─── typeof Schema.NumberFromString
// ▼
const
const from: typeof Schema.NumberFromString
from
=
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { exact: true; nullable: true; }>; }>.fields: Readonly<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>;
}>
fields
.
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
exact: true;
nullable: true;
}>
quantity
.
optionalWith<typeof NumberFromString, { exact: true; nullable: true; }>.from: typeof Schema.NumberFromString
from

当创建模式来复制包含never类型可选字段的TypeScript类型时,例如:

type MyType = {
readonly quantity?: never
}

这些字段的处理取决于您的tsconfig.json中的exactOptionalPropertyTypes设置。 此设置影响模式是否应将可选的never类型字段视为简单缺失或允许undefined作为值。

示例exactOptionalPropertyTypes: false

当此功能关闭时,您可以使用Schema.optional函数。这种方法允许字段隐式接受undefined作为值。

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.Never>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optional<typeof Schema.Never>;
}>(fields: {
quantity: Schema.optional<typeof Schema.Never>;
}): Schema.Struct<{
quantity: Schema.optional<typeof Schema.Never>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optional<typeof Schema.Never>
quantity
:
import Schema
Schema
.
const optional: <typeof Schema.Never>(self: typeof Schema.Never) => Schema.optional<typeof Schema.Never>

@since3.10.0

optional
(
import Schema
Schema
.
class Never

@since3.10.0

Never
)
})
// ┌─── { readonly quantity?: undefined; }
// ▼
type
type Encoded = {
readonly quantity?: undefined;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.Never>;
}>
Product
.
Schema<{ readonly quantity?: undefined; }, { readonly quantity?: undefined; }, never>.Encoded: {
readonly quantity?: undefined;
}
Encoded
// ┌─── { readonly quantity?: undefined; }
// ▼
type
type Type = {
readonly quantity?: undefined;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optional<typeof Schema.Never>;
}>
Product
.
Schema<{ readonly quantity?: undefined; }, { readonly quantity?: undefined; }, never>.Type: {
readonly quantity?: undefined;
}
Type

示例exactOptionalPropertyTypes: true

当此功能开启时,建议使用Schema.optionalWith函数。 它确保更严格地强制字段的缺失。

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.Never, {
exact: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.Never, {
exact: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.Never, {
exact: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.Never, {
exact: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.Never, {
exact: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.Never, {
exact: true;
}>(self: typeof Schema.Never, options: {
exact: true;
}) => Schema.optionalWith<typeof Schema.Never, {
exact: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
import Schema
Schema
.
class Never

@since3.10.0

Never
, {
exact: true
exact
: true })
})
// ┌─── { readonly quantity?: never; }
// ▼
type
type Encoded = {
readonly quantity?: never;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.Never, {
exact: true;
}>;
}>
Product
.
Schema<{ readonly quantity?: never; }, { readonly quantity?: never; }, never>.Encoded: {
readonly quantity?: never;
}
Encoded
// ┌─── { readonly quantity?: never; }
// ▼
type
type Type = {
readonly quantity?: never;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.Never, {
exact: true;
}>;
}>
Product
.
Schema<{ readonly quantity?: never; }, { readonly quantity?: never; }, never>.Type: {
readonly quantity?: never;
}
Type

Schema.optionalWith中的default选项允许您设置在解码和对象构造阶段应用的默认值。 此功能确保即使用户未提供某些属性,系统也会自动使用指定的默认值。

Schema.optionalWith函数提供了几种方式来控制在解码和编码期间如何应用默认值。您可以微调是否仅在输入完全缺失时应用默认值,或者甚至在提供nullundefined值时也应用默认值。

这是最简单的用例。如果输入缺失或为undefined,将应用默认值。

语法

Schema.optionalWith(schema: Schema<A, I, R>, { default: () => A })
操作行为
解码如果输入缺失或为undefined,则应用默认值
编码将输入a: A转换回i: I

示例(当字段缺失或为undefined时应用默认值)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
default: () => number;
}>(self: typeof Schema.NumberFromString, options: {
default: () => number;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
default: () => number
default
: () => 1 // Default value for quantity
})
})
// ┌─── { readonly quantity?: string | undefined; }
// ▼
type
type Encoded = {
readonly quantity?: string | undefined;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
.
Schema<{ readonly quantity: number; }, { readonly quantity?: string | undefined; }, never>.Encoded: {
readonly quantity?: string | undefined;
}
Encoded
// ┌─── { readonly quantity: number; }
// ▼
type
type Type = {
readonly quantity: number;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
.
Schema<{ readonly quantity: number; }, { readonly quantity?: string | undefined; }, never>.Type: {
readonly quantity: number;
}
Type
// 应用默认值的解码示例
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
)({}))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
)({
quantity: string
quantity
: "2" }))
// Output: { quantity: 2 }
// 应用默认值的对象构造示例
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 Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { default: () => number; }>; }>.make(props: void | {
readonly quantity?: number;
}, options?: Schema.MakeOptions): {
readonly quantity: number;
}
make
({}))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { default: () => number; }>; }>.make(props: void | {
readonly quantity?: number;
}, options?: Schema.MakeOptions): {
readonly quantity: number;
}
make
({
quantity?: number
quantity
: 2 }))
// Output: { quantity: 2 }

您可以使用from属性访问原始模式类型(在标记为可选之前)。

示例(访问原始模式)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
default: () => number;
}>(self: typeof Schema.NumberFromString, options: {
default: () => number;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
default: () => number
default
: () => 1 // Default value for quantity
})
})
// ┌─── typeof Schema.NumberFromString
// ▼
const
const from: typeof Schema.NumberFromString
from
=
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { default: () => number; }>; }>.fields: Readonly<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>;
}>
fields
.
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
}>
quantity
.
optionalWith<typeof NumberFromString, { default: () => number; }>.from: typeof Schema.NumberFromString
from

当您希望仅在字段完全缺失时(而不是在为undefined时)应用默认值时,可以使用exact选项。

语法

Schema.optionalWith(schema: Schema<A, I, R>, {
default: () => A,
exact: true
})
操作行为
解码仅在输入缺失时应用默认值
编码将输入a: A转换回i: I

示例(仅在字段缺失时应用默认值)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>(self: typeof Schema.NumberFromString, options: {
default: () => number;
exact: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
default: () => number
default
: () => 1, // Default value for quantity
exact: true
exact
: true // Only apply default if quantity is not provided
})
})
// ┌─── { readonly quantity?: string; }
// ▼
type
type Encoded = {
readonly quantity?: string;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>;
}>
Product
.
Schema<{ readonly quantity: number; }, { readonly quantity?: string; }, never>.Encoded: {
readonly quantity?: string;
}
Encoded
// ┌─── { readonly quantity: number; }
// ▼
type
type Type = {
readonly quantity: number;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>;
}>
Product
.
Schema<{ readonly quantity: number; }, { readonly quantity?: string; }, never>.Type: {
readonly quantity: number;
}
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>;
}>
Product
)({}))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>;
}>
Product
)({
quantity: string
quantity
: "2" }))
// Output: { quantity: 2 }
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<{
readonly quantity: number;
}, {
readonly quantity?: string;
}>(schema: Schema.Schema<{
readonly quantity: number;
}, {
readonly quantity?: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
/*
throws:
ParseError: (Struct (Encoded side) <-> Struct (Type side))
└─ Encoded side transformation failure
└─ Struct (Encoded side)
└─ ["quantity"]
└─ NumberFromString
└─ Encoded side transformation failure
└─ Expected string, actual undefined
*/

在您希望null值触发默认行为的情况下,可以使用nullable选项。这确保如果字段设置为null,它将被默认值替换。

语法

Schema.optionalWith(schema: Schema<A, I, R>, {
default: () => A,
nullable: true
})
操作行为
解码如果输入缺失或为undefinednull,则应用默认值
编码将输入a: A转换回i: I

示例(当字段缺失或为undefinednull时应用默认值)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
default: () => number;
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
default: () => number
default
: () => 1, // Default value for quantity
nullable: true
nullable
: true // Apply default if quantity is null
})
})
// ┌─── { readonly quantity?: string | null | undefined; }
// ▼
type
type Encoded = {
readonly quantity?: string | null | undefined;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity: number; }, { readonly quantity?: string | null | undefined; }, never>.Encoded: {
readonly quantity?: string | null | undefined;
}
Encoded
// ┌─── { readonly quantity: number; }
// ▼
type
type Type = {
readonly quantity: number;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity: number; }, { readonly quantity?: string | null | undefined; }, never>.Type: {
readonly quantity: number;
}
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly quantity: number;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity: number;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}>
Product
)({}))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly quantity: number;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity: number;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly quantity: number;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity: number;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}>
Product
)({
quantity: null
quantity
: null }))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly quantity: number;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity: number;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
nullable: true;
}>;
}>
Product
)({
quantity: string
quantity
: "2" }))
// Output: { quantity: 2 }

为了更严格的方法,您可以同时组合exactnullable选项。这样,默认值仅在字段为null或缺失时应用,而不是在明确设置为undefined时应用。

语法

Schema.optionalWith(schema: Schema<A, I, R>, {
default: () => A,
exact: true,
nullable: true
})
操作行为
解码如果输入缺失或为null,则应用默认值
编码将输入a: A转换回i: I

示例(仅在字段缺失或为null时应用默认值)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
default: () => number;
exact: true;
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
default: () => number
default
: () => 1, // Default value for quantity
exact: true
exact
: true, // Only apply default if quantity is not provided
nullable: true
nullable
: true // Apply default if quantity is null
})
})
// ┌─── { readonly quantity?: string | null; }
// ▼
type
type Encoded = {
readonly quantity?: string | null;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity: number; }, { readonly quantity?: string | null; }, never>.Encoded: {
readonly quantity?: string | null;
}
Encoded
// ┌─── { readonly quantity: number; }
// ▼
type
type Type = {
readonly quantity: number;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity: number; }, { readonly quantity?: string | null; }, never>.Type: {
readonly quantity: number;
}
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}>
Product
)({}))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity: null
quantity
: null }))
// Output: { quantity: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity: string
quantity
: "2" }))
// Output: { quantity: 2 }
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<{
readonly quantity: number;
}, {
readonly quantity?: string | null;
}>(schema: Schema.Schema<{
readonly quantity: number;
}, {
readonly quantity?: string | null;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
default: () => number;
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
/*
throws:
ParseError: (Struct (Encoded side) <-> Struct (Type side))
└─ Encoded side transformation failure
└─ Struct (Encoded side)
└─ ["quantity"]
└─ NumberFromString
└─ Encoded side transformation failure
└─ Expected string, actual undefined
*/

在处理可选字段时,您可能希望将它们作为Option类型处理。这种方法允许您明确管理字段的存在或缺失,而不是依赖于undefinednull

您可以配置模式将可选字段视为Option类型,其中缺失或undefined值转换为Option.none(),现有值包装在Option.some()中。

语法

optionalWith(schema: Schema<A, I, R>, { as: "Option" })
输入输出
<缺失值>转换为Option.none()
undefined转换为Option.none()
i: I转换为Option.some(a: A)
输入输出
Option.none()转换为<缺失值>
Option.some(a: A)转换回i: I

示例(将可选字段作为Option处理)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
as: "Option";
}>(self: typeof Schema.NumberFromString, options: {
as: "Option";
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
as: "Option"
as
: "Option" })
})
// ┌─── { readonly quantity?: string | undefined; }
// ▼
type
type Encoded = {
readonly quantity?: string | undefined;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>
Product
.
Schema<{ readonly quantity: Option<number>; }, { readonly quantity?: string | undefined; }, never>.Encoded: {
readonly quantity?: string | undefined;
}
Encoded
// ┌─── { readonly quantity: Option<number>; }
// ▼
type
type Type = {
readonly quantity: Option<number>;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>
Product
.
Schema<{ readonly quantity: Option<number>; }, { readonly quantity?: string | undefined; }, never>.Type: {
readonly quantity: Option<number>;
}
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | undefined;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>
Product
)({}))
// Output: { quantity: { _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 Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | undefined;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
// Output: { quantity: { _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 Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | undefined;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>
Product
)({
quantity: string
quantity
: "2" }))
// Output: { quantity: { _id: 'Option', _tag: 'Some', value: 2 } }

您可以使用from属性访问原始模式类型(在标记为可选之前)。

示例(访问原始模式)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
as: "Option";
}>(self: typeof Schema.NumberFromString, options: {
as: "Option";
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
as: "Option"
as
: "Option" })
})
// ┌─── typeof Schema.NumberFromString
// ▼
const
const from: typeof Schema.NumberFromString
from
=
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { as: "Option"; }>; }>.fields: Readonly<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>;
}>
fields
.
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
}>
quantity
.
optionalWith<typeof NumberFromString, { as: "Option"; }>.from: typeof Schema.NumberFromString
from

exact选项确保可选字段的默认行为仅在字段完全缺失时应用,而不是在为undefined时应用。

语法

optionalWith(schema: Schema<A, I, R>, {
as: "Option",
exact: true
})
输入输出
<缺失值>转换为Option.none()
undefinedParseError
i: I转换为Option.some(a: A)
输入输出
Option.none()转换为<缺失值>
Option.some(a: A)转换回i: I

示例(在可选字段作为Option时使用精确性)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>(self: typeof Schema.NumberFromString, options: {
as: "Option";
exact: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
as: "Option"
as
: "Option",
exact: true
exact
: true
})
})
// ┌─── { readonly quantity?: string; }
// ▼
type
type Encoded = {
readonly quantity?: string;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>
Product
.
Schema<{ readonly quantity: Option<number>; }, { readonly quantity?: string; }, never>.Encoded: {
readonly quantity?: string;
}
Encoded
// ┌─── { readonly quantity: Option<number>; }
// ▼
type
type Type = {
readonly quantity: Option<number>;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>
Product
.
Schema<{ readonly quantity: Option<number>; }, { readonly quantity?: string; }, never>.Type: {
readonly quantity: Option<number>;
}
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>
Product
)({}))
// Output: { quantity: { _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 Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>
Product
)({
quantity: string
quantity
: "2" }))
// Output: { quantity: { _id: 'Option', _tag: 'Some', value: 2 } }
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<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
/*
throws:
ParseError: (Struct (Encoded side) <-> Struct (Type side))
└─ Encoded side transformation failure
└─ Struct (Encoded side)
└─ ["quantity"]
└─ NumberFromString
└─ Encoded side transformation failure
└─ Expected string, actual undefined
*/

您可以使用from属性访问原始模式类型(在标记为可选之前)。

示例(访问原始模式)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>(self: typeof Schema.NumberFromString, options: {
as: "Option";
exact: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
as: "Option"
as
: "Option",
exact: true
exact
: true
})
})
// ┌─── typeof Schema.NumberFromString
// ▼
const
const from: typeof Schema.NumberFromString
from
=
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { as: "Option"; exact: true; }>; }>.fields: Readonly<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>;
}>
fields
.
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
}>
quantity
.
optionalWith<typeof NumberFromString, { as: "Option"; exact: true; }>.from: typeof Schema.NumberFromString
from

nullable选项扩展了默认行为,将null视为等同于Option.none(),与缺失或undefined值一起处理。

语法

optionalWith(schema: Schema<A, I, R>, {
as: "Option",
nullable: true
})
输入输出
<缺失值>转换为Option.none()
undefined转换为Option.none()
null转换为Option.none()
i: I转换为Option.some(a: A)
输入输出
Option.none()转换为<缺失值>
Option.some(a: A)转换回i: I

示例(在可选字段作为Option时将Null处理为缺失值)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
as: "Option";
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
as: "Option"
as
: "Option",
nullable: true
nullable
: true
})
})
// ┌─── { readonly quantity?: string | null | undefined; }
// ▼
type
type Encoded = {
readonly quantity?: string | null | undefined;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity: Option<number>; }, { readonly quantity?: string | null | undefined; }, never>.Encoded: {
readonly quantity?: string | null | undefined;
}
Encoded
// ┌─── { readonly quantity: Option<number>; }
// ▼
type
type Type = {
readonly quantity: Option<number>;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity: Option<number>; }, { readonly quantity?: string | null | undefined; }, never>.Type: {
readonly quantity: Option<number>;
}
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
Product
)({}))
// Output: { quantity: { _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 Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
// Output: { quantity: { _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 Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
Product
)({
quantity: null
quantity
: null }))
// Output: { quantity: { _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 Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null | undefined;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null | undefined;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
Product
)({
quantity: string
quantity
: "2" }))
// Output: { quantity: { _id: 'Option', _tag: 'Some', value: 2 } }

您可以使用from属性访问原始模式类型(在标记为可选之前)。

示例(访问原始模式)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
as: "Option";
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
as: "Option"
as
: "Option",
nullable: true
nullable
: true
})
})
// ┌─── typeof Schema.NumberFromString
// ▼
const
const from: typeof Schema.NumberFromString
from
=
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { as: "Option"; nullable: true; }>; }>.fields: Readonly<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>;
}>
fields
.
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
nullable: true;
}>
quantity
.
optionalWith<typeof NumberFromString, { as: "Option"; nullable: true; }>.from: typeof Schema.NumberFromString
from

当同时使用exactnullable选项时,只有null和缺失字段被视为Option.none(),而undefined被视为无效值。

语法

optionalWith(schema: Schema<A, I, R>, {
as: "Option",
exact: true,
nullable: true
})
输入输出
<缺失值>转换为Option.none()
undefinedParseError
null转换为Option.none()
i: I转换为Option.some(a: A)
输入输出
Option.none()转换为<缺失值>
Option.some(a: A)转换回i: I

示例(在可选字段作为Option时使用精确性并将Null处理为缺失值)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
as: "Option";
exact: true;
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
as: "Option"
as
: "Option",
exact: true
exact
: true,
nullable: true
nullable
: true
})
})
// ┌─── { readonly quantity?: string | null; }
// ▼
type
type Encoded = {
readonly quantity?: string | null;
}
Encoded
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity: Option<number>; }, { readonly quantity?: string | null; }, never>.Encoded: {
readonly quantity?: string | null;
}
Encoded
// ┌─── { readonly quantity: Option<number>; }
// ▼
type
type Type = {
readonly quantity: Option<number>;
}
Type
= typeof
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
Product
.
Schema<{ readonly quantity: Option<number>; }, { readonly quantity?: string | null; }, never>.Type: {
readonly quantity: Option<number>;
}
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
Product
)({}))
// Output: { quantity: { _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 Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity: null
quantity
: null }))
// Output: { quantity: { _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 Schema
Schema
.
decodeUnknownSync<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity: string
quantity
: "2" }))
// Output: { quantity: { _id: 'Option', _tag: 'Some', value: 2 } }
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<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null;
}>(schema: Schema.Schema<{
readonly quantity: Option<number>;
}, {
readonly quantity?: string | null;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly quantity: Option<number>;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
Product
)({
quantity: undefined
quantity
:
var undefined
undefined
}))
/*
throws:
ParseError: (Struct (Encoded side) <-> Struct (Type side))
└─ Encoded side transformation failure
└─ Struct (Encoded side)
└─ ["quantity"]
└─ NumberFromString
└─ Encoded side transformation failure
└─ Expected string, actual undefined
*/

您可以使用from属性访问原始模式类型(在标记为可选之前)。

示例(访问原始模式)

import {
import Schema
Schema
} from "effect"
const
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
Product
=
import Schema
Schema
.
function Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>(fields: {
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}): Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}> (+1 overload)

@since3.10.0

Struct
({
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>
quantity
:
import Schema
Schema
.
const optionalWith: <typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>(self: typeof Schema.NumberFromString, options: {
as: "Option";
exact: true;
nullable: true;
}) => Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}> (+1 overload)

@since3.10.0

optionalWith
(
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
, {
as: "Option"
as
: "Option",
exact: true
exact
: true,
nullable: true
nullable
: true
})
})
// ┌─── typeof Schema.NumberFromString
// ▼
const
const from: typeof Schema.NumberFromString
from
=
const Product: Schema.Struct<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
Product
.
Struct<{ quantity: optionalWith<typeof NumberFromString, { as: "Option"; exact: true; nullable: true; }>; }>.fields: Readonly<{
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>;
}>
fields
.
quantity: Schema.optionalWith<typeof Schema.NumberFromString, {
as: "Option";
exact: true;
nullable: true;
}>
quantity
.
optionalWith<typeof NumberFromString, { as: "Option"; exact: true; nullable: true; }>.from: typeof Schema.NumberFromString
from

Schema.optionalToOptional API允许您管理从输入中的可选字段到输出中的可选字段的转换。这对于根据特定条件控制输出类型以及字段是否存在或缺失非常有用。

optionalToOptional的一个常见用例是处理特定输入值(如空字符串)应在输出中被视为缺失字段的字段。

语法

const optionalToOptional = <FA, FI, FR, TA, TI, TR>(
from: Schema<FA, FI, FR>,
to: Schema<TA, TI, TR>,
options: {
readonly decode: (o: Option.Option<FA>) => Option.Option<TI>,
readonly encode: (o: Option.Option<TI>) => Option.Option<FA>
}
): PropertySignature<"?:", TA, never, "?:", FI, false, FR | TR>

在此函数中:

  • from参数指定输入模式,to指定输出模式。
  • decodeencode函数定义字段在两侧应如何解释:
    • Option.none()作为输入参数表示输入中缺失字段。
    • 从任一函数返回Option.none()将在输出中省略该字段。

示例(从输出中省略空字符串)

考虑一个类型为string的可选字段,其中输入中的空字符串应从输出中删除。

import {
import Option

@since2.0.0

@since2.0.0

Option
,
import Schema
Schema
} from "effect"
const
const schema: Schema.Struct<{
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}>
schema
=
import Schema
Schema
.
function Struct<{
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}>(fields: {
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}): Schema.Struct<{
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}> (+1 overload)

@since3.10.0

Struct
({
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>
nonEmpty
:
import Schema
Schema
.
const optionalToOptional: <string, string, never, string, string, never>(from: Schema.Schema<string, string, never>, to: Schema.Schema<string, string, never>, options: {
readonly decode: (o: Option.Option<string>) => Option.Option<string>;
readonly encode: (o: Option.Option<string>) => Option.Option<string>;
}) => Schema.PropertySignature<"?:", string, never, "?:", string, false, never>

Converts an optional property to another optional property through a transformation Option -> Option.

  • decode:
    • none as argument means the value is missing in the input.
    • none as return value means the value will be missing in the output.
  • encode:
    • none as argument means the value is missing in the input.
    • none as return value means the value will be missing in the output.

@since3.10.0

optionalToOptional
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
import Schema
Schema
.
class String
export String

@since3.10.0

String
, {
// ┌─── Option<string>
// ▼
decode: (o: Option.Option<string>) => Option.Option<string>
decode
: (
maybeString: Option.Option<string>
maybeString
) => {
if (
import Option

@since2.0.0

@since2.0.0

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

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

@example

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

@seeisSome for the opposite check.

@since2.0.0

isNone
(
maybeString: Option.Option<string>
maybeString
)) {
// 如果`maybeString`是`None`,则字段在输入中缺失。
// 返回Option.none()以在输出中省略它。
return
import Option

@since2.0.0

@since2.0.0

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

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

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

Example (Creating an Option with No Value)

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

@seesome for the opposite operation.

@since2.0.0

none
()
}
// 从`Some`实例中提取值
const
const value: string
value
=
maybeString: Option.Some<string>
maybeString
.
Some<string>.value: string
value
if (
const value: string
value
=== "") {
// 通过返回Option.none()将空字符串视为输出中的缺失。
return
import Option

@since2.0.0

@since2.0.0

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

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

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

Example (Creating an Option with No Value)

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

@seesome for the opposite operation.

@since2.0.0

none
()
}
// 在输出中包含非空字符串。
return
import Option

@since2.0.0

@since2.0.0

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

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

Example (Creating an Option with a Value)

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

@seenone for the opposite operation.

@since2.0.0

some
(
const value: string
value
)
},
// 在编码阶段,您可以决定以类似于解码阶段的方式处理字段
// 或使用不同的逻辑。
// 这里,逻辑保持不变。
//
// ┌─── Option<string>
// ▼
encode: (o: Option.Option<string>) => Option.Option<string>
encode
: (
maybeString: Option.Option<string>
maybeString
) =>
maybeString: Option.Option<string>
maybeString
})
})
// 解码示例
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
decode
=
import Schema
Schema
.
decodeUnknownSync<{
readonly nonEmpty?: string;
}, {
readonly nonEmpty?: string;
}>(schema: Schema.Schema<{
readonly nonEmpty?: string;
}, {
readonly nonEmpty?: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Struct<{
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}>
schema
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
decode
({}))
// Output: {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
decode
({
nonEmpty: string
nonEmpty
: "" }))
// Output: {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
decode
({
nonEmpty: string
nonEmpty
: "a non-empty string" }))
// Output: { nonEmpty: 'a non-empty string' }
// 编码示例
const
const encode: (a: {
readonly nonEmpty?: string;
}, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
encode
=
import Schema
Schema
.
encodeSync<{
readonly nonEmpty?: string;
}, {
readonly nonEmpty?: string;
}>(schema: Schema.Schema<{
readonly nonEmpty?: string;
}, {
readonly nonEmpty?: string;
}, never>, options?: ParseOptions): (a: {
readonly nonEmpty?: string;
}, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
export encodeSync

@since3.10.0

encodeSync
(
const schema: Schema.Struct<{
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}>
schema
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const encode: (a: {
readonly nonEmpty?: string;
}, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
encode
({}))
// Output: {}
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const encode: (a: {
readonly nonEmpty?: string;
}, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
encode
({
nonEmpty?: string
nonEmpty
: "" }))
// Output: { nonEmpty: '' }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const encode: (a: {
readonly nonEmpty?: string;
}, overrideOptions?: ParseOptions) => {
readonly nonEmpty?: string;
}
encode
({
nonEmpty?: string
nonEmpty
: "a non-empty string" }))
// Output: { nonEmpty: 'a non-empty string' }

您可以使用Option.filter简化解码逻辑,它以简洁的方式过滤掉不需要的值。

示例(使用Option.filter进行解码)

import {
const identity: <A>(a: A) => A

The identity function, i.e. A function that returns its input argument.

@example

import * as assert from "node:assert"
import { identity } from "effect/Function"
assert.deepStrictEqual(identity(5), 5)

@since2.0.0

identity
,
import Option

@since2.0.0

@since2.0.0

Option
,
import Schema
Schema
} from "effect"
const
const schema: Schema.Struct<{
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}>
schema
=
import Schema
Schema
.
function Struct<{
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}>(fields: {
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}): Schema.Struct<{
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>;
}> (+1 overload)

@since3.10.0

Struct
({
nonEmpty: Schema.PropertySignature<"?:", string, never, "?:", string, false, never>
nonEmpty
:
import Schema
Schema
.
const optionalToOptional: <string, string, never, string, string, never>(from: Schema.Schema<string, string, never>, to: Schema.Schema<string, string, never>, options: {
readonly decode: (o: Option.Option<string>) => Option.Option<string>;
readonly encode: (o: Option.Option<string>) => Option.Option<string>;
}) => Schema.PropertySignature<"?:", string, never, "?:", string, false, never>

Converts an optional property to another optional property through a transformation Option -> Option.

  • decode:
    • none as argument means the value is missing in the input.
    • none as return value means the value will be missing in the output.
  • encode:
    • none as argument means the value is missing in the input.
    • none as return value means the value will be missing in the output.

@since3.10.0

optionalToOptional
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
import Schema
Schema
.
class String
export String

@since3.10.0

String
, {
decode: (o: Option.Option<string>) => Option.Option<string>
decode
:
import Option

@since2.0.0

@since2.0.0

Option
.
const filter: <string>(predicate: Predicate<string>) => (self: Option.Option<string>) => Option.Option<string> (+3 overloads)

Filters an Option using a predicate. If the predicate is not satisfied or the Option is None returns None.

If you need to change the type of the Option in addition to filtering, see filterMap.

@example

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

@since2.0.0

filter
((
s: string
s
) =>
s: string
s
!== ""),
encode: (o: Option.Option<string>) => Option.Option<string>
encode
:
const identity: <A>(a: A) => A

The identity function, i.e. A function that returns its input argument.

@example

import * as assert from "node:assert"
import { identity } from "effect/Function"
assert.deepStrictEqual(identity(5), 5)

@since2.0.0

identity
})
})

Schema.optionalToRequired API允许您将可选字段转换为必需字段,并使用自定义逻辑处理输入中字段缺失的情况。

语法

const optionalToRequired = <FA, FI, FR, TA, TI, TR>(
from: Schema<FA, FI, FR>,
to: Schema<TA, TI, TR>,
options: {
readonly decode: (o: Option.Option<FA>) => TI,
readonly encode: (ti: TI) => Option.Option<FA>
}
): PropertySignature<":", TA, never, "?:", FI, false, FR | TR>

在此函数中:

  • from指定输入模式,而to指定输出模式。
  • decodeencode函数定义转换行为:
    • Option.none()传递给decode意味着字段在输入中缺失。然后函数可以为输出返回默认值。
    • encode中返回Option.none()将在输出中省略该字段。

示例(为缺失字段设置null作为默认值)

此示例演示如何使用optionalToRequired在输入中缺失nullable字段时提供null默认值。在编码期间,值为null的字段将从输出中省略。

import {
import Option

@since2.0.0

@since2.0.0

Option
,
import Schema
Schema
} from "effect"
const
const schema: Schema.Struct<{
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}>
schema
=
import Schema
Schema
.
function Struct<{
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}>(fields: {
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}): Schema.Struct<{
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}> (+1 overload)

@since3.10.0

Struct
({
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>
nullable
:
import Schema
Schema
.
const optionalToRequired: <string, string, never, string | null, string | null, never>(from: Schema.Schema<string, string, never>, to: Schema.Schema<string | null, string | null, never>, options: {
readonly decode: (o: Option.Option<string>) => string | null;
readonly encode: (ti: string | null) => Option.Option<string>;
}) => Schema.PropertySignature<":", string | null, never, "?:", string, false, never>

Converts an optional property to a required one through a transformation Option -> Type.

  • decode: none as argument means the value is missing in the input.
  • encode: none as return value means the value will be missing in the output.

@since3.10.0

optionalToRequired
(
// 可选字符串的输入模式
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
// 允许null或字符串的输出模式
import Schema
Schema
.
const NullOr: <typeof Schema.String>(self: typeof Schema.String) => Schema.NullOr<typeof Schema.String>

@since3.10.0

NullOr
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
),
{
// ┌─── Option<string>
// ▼
decode: (o: Option.Option<string>) => string | null
decode
: (
maybeString: Option.Option<string>
maybeString
) => {
if (
import Option

@since2.0.0

@since2.0.0

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

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

@example

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

@seeisSome for the opposite check.

@since2.0.0

isNone
(
maybeString: Option.Option<string>
maybeString
)) {
// 如果`maybeString`是`None`,则字段在输入中缺失。
// 返回`null`作为输出的默认值。
return null
}
// 从`Some`实例中提取值
// 并将其用作输出。
return
maybeString: Option.Some<string>
maybeString
.
Some<string>.value: string
value
},
// 在编码期间,将`null`视为缺失字段
//
// ┌─── string | null
// ▼
encode: (ti: string | null) => Option.Option<string>
encode
: (
stringOrNull: string | null
stringOrNull
) =>
stringOrNull: string | null
stringOrNull
=== null
? // 通过返回`None`省略字段
import Option

@since2.0.0

@since2.0.0

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

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

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

Example (Creating an Option with No Value)

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

@seesome for the opposite operation.

@since2.0.0

none
()
: // 通过返回`Some`包含字段
import Option

@since2.0.0

@since2.0.0

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

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

Example (Creating an Option with a Value)

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

@seenone for the opposite operation.

@since2.0.0

some
(
stringOrNull: string
stringOrNull
)
}
)
})
// 解码示例
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly nullable: string | null;
}
decode
=
import Schema
Schema
.
decodeUnknownSync<{
readonly nullable: string | null;
}, {
readonly nullable?: string;
}>(schema: Schema.Schema<{
readonly nullable: string | null;
}, {
readonly nullable?: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly nullable: string | null;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Struct<{
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}>
schema
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly nullable: string | null;
}
decode
({}))
// Output: { nullable: null }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly nullable: string | null;
}
decode
({
nullable: string
nullable
: "a value" }))
// Output: { nullable: 'a value' }
// 编码示例
const
const encode: (a: {
readonly nullable: string | null;
}, overrideOptions?: ParseOptions) => {
readonly nullable?: string;
}
encode
=
import Schema
Schema
.
encodeSync<{
readonly nullable: string | null;
}, {
readonly nullable?: string;
}>(schema: Schema.Schema<{
readonly nullable: string | null;
}, {
readonly nullable?: string;
}, never>, options?: ParseOptions): (a: {
readonly nullable: string | null;
}, overrideOptions?: ParseOptions) => {
readonly nullable?: string;
}
export encodeSync

@since3.10.0

encodeSync
(
const schema: Schema.Struct<{
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}>
schema
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const encode: (a: {
readonly nullable: string | null;
}, overrideOptions?: ParseOptions) => {
readonly nullable?: string;
}
encode
({
nullable: string | null
nullable
: "a value" }))
// Output: { nullable: 'a value' }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const encode: (a: {
readonly nullable: string | null;
}, overrideOptions?: ParseOptions) => {
readonly nullable?: string;
}
encode
({
nullable: string | null
nullable
: null }))
// Output: {}

您可以使用Option.getOrElseOption.liftPredicate简化解码和编码逻辑,以实现简洁和可读的转换。

示例(使用Option.getOrElseOption.liftPredicate

import {
import Option

@since2.0.0

@since2.0.0

Option
,
import Schema
Schema
} from "effect"
const
const schema: Schema.Struct<{
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}>
schema
=
import Schema
Schema
.
function Struct<{
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}>(fields: {
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}): Schema.Struct<{
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>;
}> (+1 overload)

@since3.10.0

Struct
({
nullable: Schema.PropertySignature<":", string | null, never, "?:", string, false, never>
nullable
:
import Schema
Schema
.
const optionalToRequired: <string, string, never, string | null, string | null, never>(from: Schema.Schema<string, string, never>, to: Schema.Schema<string | null, string | null, never>, options: {
readonly decode: (o: Option.Option<string>) => string | null;
readonly encode: (ti: string | null) => Option.Option<string>;
}) => Schema.PropertySignature<":", string | null, never, "?:", string, false, never>

Converts an optional property to a required one through a transformation Option -> Type.

  • decode: none as argument means the value is missing in the input.
  • encode: none as return value means the value will be missing in the output.

@since3.10.0

optionalToRequired
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
import Schema
Schema
.
const NullOr: <typeof Schema.String>(self: typeof Schema.String) => Schema.NullOr<typeof Schema.String>

@since3.10.0

NullOr
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
),
{
decode: (o: Option.Option<string>) => string | null
decode
:
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrElse: <null>(onNone: LazyArg<null>) => <A>(self: Option.Option<A>) => A | null (+1 overload)

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

Details

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

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

@example

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

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

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

@since2.0.0

getOrElse
(() => null),
encode: (ti: string | null) => Option.Option<string>
encode
:
import Option

@since2.0.0

@since2.0.0

Option
.
const liftPredicate: <string | null, string>(refinement: Refinement<string | null, string>) => (a: string | null) => Option.Option<string> (+3 overloads)
liftPredicate
((
value: string | null
value
) =>
value: string | null
value
!== null)
}
)
})

requiredToOptional API允许您将必需字段转换为可选字段,应用自定义逻辑来确定何时可以省略该字段。

语法

const requiredToOptional = <FA, FI, FR, TA, TI, TR>(
from: Schema<FA, FI, FR>,
to: Schema<TA, TI, TR>,
options: {
readonly decode: (fa: FA) => Option.Option<TI>
readonly encode: (o: Option.Option<TI>) => FA
}
): PropertySignature<"?:", TA, never, ":", FI, false, FR | TR>

使用decodeencode函数,您可以控制字段的存在或缺失:

  • decode中的Option.none()作为参数意味着字段在输入中缺失。
  • encode中的Option.none()作为返回值意味着字段将在输出中省略。

示例(将空字符串处理为缺失值)

在此示例中,name字段是必需的,但如果它是空字符串,则被视为可选。在解码期间,name中的空字符串被视为缺失,而编码确保有值(如果name缺失,则使用空字符串作为默认值)。

import {
import Option

@since2.0.0

@since2.0.0

Option
,
import Schema
Schema
} from "effect"
const
const schema: Schema.Struct<{
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}>
schema
=
import Schema
Schema
.
function Struct<{
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}>(fields: {
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}): Schema.Struct<{
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}> (+1 overload)

@since3.10.0

Struct
({
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>
name
:
import Schema
Schema
.
const requiredToOptional: <string, string, never, string, string, never>(from: Schema.Schema<string, string, never>, to: Schema.Schema<string, string, never>, options: {
readonly decode: (fa: string) => Option.Option<string>;
readonly encode: (o: Option.Option<string>) => string;
}) => Schema.PropertySignature<"?:", string, never, ":", string, false, never>

Converts an optional property to a required one through a transformation Type -> Option.

  • decode: none as return value means the value will be missing in the output.
  • encode: none as argument means the value is missing in the input.

@since3.10.0

requiredToOptional
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
import Schema
Schema
.
class String
export String

@since3.10.0

String
, {
// ┌─── string
// ▼
decode: (fa: string) => Option.Option<string>
decode
: (
string: string
string
) => {
// 将空字符串视为缺失值
if (
string: string
string
=== "") {
// 通过返回`None`省略字段
return
import Option

@since2.0.0

@since2.0.0

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

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

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

Example (Creating an Option with No Value)

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

@seesome for the opposite operation.

@since2.0.0

none
()
}
// 否则,按原样返回字符串
return
import Option

@since2.0.0

@since2.0.0

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

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

Example (Creating an Option with a Value)

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

@seenone for the opposite operation.

@since2.0.0

some
(
string: string
string
)
},
// ┌─── Option<string>
// ▼
encode: (o: Option.Option<string>) => string
encode
: (
maybeString: Option.Option<string>
maybeString
) => {
// 检查字段是否缺失
if (
import Option

@since2.0.0

@since2.0.0

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

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

@example

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

@seeisSome for the opposite check.

@since2.0.0

isNone
(
maybeString: Option.Option<string>
maybeString
)) {
// 提供空字符串作为默认值
return ""
}
// 否则,按原样返回字符串
return
maybeString: Option.Some<string>
maybeString
.
Some<string>.value: string
value
}
})
})
// 解码示例
const
const decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly name?: string;
}
decode
=
import Schema
Schema
.
decodeUnknownSync<{
readonly name?: string;
}, {
readonly name: string;
}>(schema: Schema.Schema<{
readonly name?: string;
}, {
readonly name: string;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name?: string;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Struct<{
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}>
schema
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly name?: string;
}
decode
({
name: string
name
: "John" }))
// Output: { 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 decode: (u: unknown, overrideOptions?: ParseOptions) => {
readonly name?: string;
}
decode
({
name: string
name
: "" }))
// Output: {}
// 编码示例
const
const encode: (a: {
readonly name?: string;
}, overrideOptions?: ParseOptions) => {
readonly name: string;
}
encode
=
import Schema
Schema
.
encodeSync<{
readonly name?: string;
}, {
readonly name: string;
}>(schema: Schema.Schema<{
readonly name?: string;
}, {
readonly name: string;
}, never>, options?: ParseOptions): (a: {
readonly name?: string;
}, overrideOptions?: ParseOptions) => {
readonly name: string;
}
export encodeSync

@since3.10.0

encodeSync
(
const schema: Schema.Struct<{
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}>
schema
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const encode: (a: {
readonly name?: string;
}, overrideOptions?: ParseOptions) => {
readonly name: string;
}
encode
({
name?: string
name
: "John" }))
// Output: { 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 encode: (a: {
readonly name?: string;
}, overrideOptions?: ParseOptions) => {
readonly name: string;
}
encode
({}))
// Output: { name: '' }

您可以使用Option.liftPredicateOption.getOrElse简化解码和编码逻辑,以实现简洁和可读的转换。

示例(使用Option.liftPredicateOption.getOrElse

import {
import Option

@since2.0.0

@since2.0.0

Option
,
import Schema
Schema
} from "effect"
const
const schema: Schema.Struct<{
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}>
schema
=
import Schema
Schema
.
function Struct<{
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}>(fields: {
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}): Schema.Struct<{
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>;
}> (+1 overload)

@since3.10.0

Struct
({
name: Schema.PropertySignature<"?:", string, never, ":", string, false, never>
name
:
import Schema
Schema
.
const requiredToOptional: <string, string, never, string, string, never>(from: Schema.Schema<string, string, never>, to: Schema.Schema<string, string, never>, options: {
readonly decode: (fa: string) => Option.Option<string>;
readonly encode: (o: Option.Option<string>) => string;
}) => Schema.PropertySignature<"?:", string, never, ":", string, false, never>

Converts an optional property to a required one through a transformation Type -> Option.

  • decode: none as return value means the value will be missing in the output.
  • encode: none as argument means the value is missing in the input.

@since3.10.0

requiredToOptional
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
import Schema
Schema
.
class String
export String

@since3.10.0

String
, {
decode: (fa: string) => Option.Option<string>
decode
:
import Option

@since2.0.0

@since2.0.0

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

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

Details

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

@example

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

@since2.0.0

liftPredicate
((
s: string
s
) =>
s: string
s
!== ""),
encode: (o: Option.Option<string>) => string
encode
:
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrElse: <string>(onNone: LazyArg<string>) => <A>(self: Option.Option<A>) => string | A (+1 overload)

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

Details

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

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

@example

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

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

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

@since2.0.0

getOrElse
(() => "")
})
})

effect中的模式可以通过多种方式扩展,允许您将现有类型与其他字段或功能组合或增强。一种常见方法是使用Struct模式中可用的fields属性。此属性提供了一种便捷的方式来添加字段或合并来自不同结构的字段,同时保留原始的Struct类型。这种方法还使访问和修改字段变得更容易。

对于更复杂的情况,例如使用联合扩展结构,您可能希望使用Schema.extend函数,它在直接字段展开可能不够的场景中提供了灵活性。

Struct通过fields属性提供对其字段的访问,这允许您通过添加其他字段或组合来自多个结构的字段来扩展现有结构。

示例(添加新字段)

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

@since3.10.0

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

@since3.10.0

String
,
b: typeof Schema.String
b
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
})
const
const Extended: Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}>
Extended
=
import Schema
Schema
.
function Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}>(fields: {
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}): Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}> (+1 overload)

@since3.10.0

Struct
({
...
const Original: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
}>
Original
.
Struct<{ a: typeof String$; b: typeof String$; }>.fields: Readonly<{
a: typeof Schema.String;
b: typeof Schema.String;
}>
fields
,
// Adding new fields
c: typeof Schema.String
c
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
d: typeof Schema.String
d
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
})
// ┌─── {
// | readonly a: string;
// | readonly b: string;
// | readonly c: string;
// | readonly d: string;
// | }
// ▼
type
type Type = {
readonly a: string;
readonly b: string;
readonly c: string;
readonly d: string;
}
Type
= typeof
const Extended: Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}>
Extended
.
Schema<{ readonly a: string; readonly b: string; readonly c: string; readonly d: string; }, { readonly a: string; readonly b: string; readonly c: string; readonly d: string; }, never>.Type: {
readonly a: string;
readonly b: string;
readonly c: string;
readonly d: string;
}
Type

示例(添加额外的索引签名)

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

@since3.10.0

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

@since3.10.0

String
,
b: typeof Schema.String
b
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
})
const
const Extended: Schema.TypeLiteral<Readonly<{
a: typeof Schema.String;
b: typeof Schema.String;
}>, readonly [Schema.Record$<typeof Schema.String, typeof Schema.String>]>
Extended
=
import Schema
Schema
.
function Struct<Readonly<{
a: typeof Schema.String;
b: typeof Schema.String;
}>, readonly [Schema.Record$<typeof Schema.String, typeof Schema.String>]>(fields: Readonly<{
a: typeof Schema.String;
b: typeof Schema.String;
}>, records_0: Schema.Record$<typeof Schema.String, typeof Schema.String>): Schema.TypeLiteral<Readonly<{
a: typeof Schema.String;
b: typeof Schema.String;
}>, readonly [Schema.Record$<typeof Schema.String, typeof Schema.String>]> (+1 overload)

@since3.10.0

Struct
(
const Original: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
}>
Original
.
Struct<{ a: typeof String$; b: typeof String$; }>.fields: Readonly<{
a: typeof Schema.String;
b: typeof Schema.String;
}>
fields
,
// Adding an index signature
import Schema
Schema
.
const Record: <typeof Schema.String, typeof Schema.String>(options: {
readonly key: typeof Schema.String;
readonly value: typeof Schema.String;
}) => Schema.Record$<typeof Schema.String, typeof Schema.String>

@since3.10.0

Record
({
key: typeof Schema.String
key
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
value: typeof Schema.String
value
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
})
)
// ┌─── {
// │ readonly [x: string]: string;
// | readonly a: string;
// | readonly b: string;
// | }
// ▼
type
type Type = {
readonly [x: string]: string;
readonly a: string;
readonly b: string;
}
Type
= typeof
const Extended: Schema.TypeLiteral<Readonly<{
a: typeof Schema.String;
b: typeof Schema.String;
}>, readonly [Schema.Record$<typeof Schema.String, typeof Schema.String>]>
Extended
.
Schema<{ readonly [x: string]: string; readonly a: string; readonly b: string; }, { readonly [x: string]: string; readonly a: string; readonly b: string; }, never>.Type: {
readonly [x: string]: string;
readonly a: string;
readonly b: string;
}
Type

示例(组合来自多个Struct的字段)

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

@since3.10.0

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

@since3.10.0

String
,
b: typeof Schema.String
b
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
})
const
const Struct2: Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
}>
Struct2
=
import Schema
Schema
.
function Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
}>(fields: {
c: typeof Schema.String;
d: typeof Schema.String;
}): Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
}> (+1 overload)

@since3.10.0

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

@since3.10.0

String
,
d: typeof Schema.String
d
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
})
const
const Extended: Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}>
Extended
=
import Schema
Schema
.
function Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}>(fields: {
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}): Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}> (+1 overload)

@since3.10.0

Struct
({
...
const Struct1: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
}>
Struct1
.
Struct<{ a: typeof String$; b: typeof String$; }>.fields: Readonly<{
a: typeof Schema.String;
b: typeof Schema.String;
}>
fields
,
...
const Struct2: Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
}>
Struct2
.
Struct<{ c: typeof String$; d: typeof String$; }>.fields: Readonly<{
c: typeof Schema.String;
d: typeof Schema.String;
}>
fields
})
// ┌─── {
// | readonly a: string;
// | readonly b: string;
// | readonly c: string;
// | readonly d: string;
// | }
// ▼
type
type Type = {
readonly a: string;
readonly b: string;
readonly c: string;
readonly d: string;
}
Type
= typeof
const Extended: Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.String;
a: typeof Schema.String;
b: typeof Schema.String;
}>
Extended
.
Schema<{ readonly a: string; readonly b: string; readonly c: string; readonly d: string; }, { readonly a: string; readonly b: string; readonly c: string; readonly d: string; }, never>.Type: {
readonly a: string;
readonly b: string;
readonly c: string;
readonly d: string;
}
Type

Schema.extend函数提供了一种结构化的方法来扩展模式,特别是在直接字段展开不够用时——例如当您需要使用其他结构的联合来扩展结构时。

支持的扩展包括:

  • Schema.String与另一个Schema.String细化或字符串字面量
  • Schema.Number与另一个Schema.Number细化或数字字面量
  • Schema.Boolean与另一个Schema.Boolean细化或布尔字面量
  • 结构与另一个结构,其中重叠字段支持扩展
  • 结构与索引签名
  • 结构与支持的模式联合
  • 结构的细化与支持的模式
  • 结构的suspend与支持的模式
  • 结构之间的转换,其中”from”和”to”侧与目标结构没有重叠字段

示例(使用结构联合扩展结构)

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

@since3.10.0

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

@since3.10.0

String
})
const
const UnionOfStructs: Schema.Union<[Schema.Struct<{
b: typeof Schema.String;
}>, Schema.Struct<{
c: typeof Schema.String;
}>]>
UnionOfStructs
=
import Schema
Schema
.
function Union<[Schema.Struct<{
b: typeof Schema.String;
}>, Schema.Struct<{
c: typeof Schema.String;
}>]>(members_0: Schema.Struct<{
b: typeof Schema.String;
}>, members_1: Schema.Struct<{
c: typeof Schema.String;
}>): Schema.Union<[Schema.Struct<{
b: typeof Schema.String;
}>, Schema.Struct<{
c: typeof Schema.String;
}>]> (+3 overloads)

@since3.10.0

Union
(
import Schema
Schema
.
function Struct<{
b: typeof Schema.String;
}>(fields: {
b: typeof Schema.String;
}): Schema.Struct<{
b: typeof Schema.String;
}> (+1 overload)

@since3.10.0

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

@since3.10.0

String
}),
import Schema
Schema
.
function Struct<{
c: typeof Schema.String;
}>(fields: {
c: typeof Schema.String;
}): Schema.Struct<{
c: typeof Schema.String;
}> (+1 overload)

@since3.10.0

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

@since3.10.0

String
})
)
const
const Extended: Schema.extend<Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Union<[Schema.Struct<{
b: typeof Schema.String;
}>, Schema.Struct<{
c: typeof Schema.String;
}>]>>
Extended
=
import Schema
Schema
.
const extend: <Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Union<[Schema.Struct<{
b: typeof Schema.String;
}>, Schema.Struct<{
c: typeof Schema.String;
}>]>>(self: Schema.Struct<{
a: typeof Schema.String;
}>, that: Schema.Union<[Schema.Struct<{
b: typeof Schema.String;
}>, Schema.Struct<{
c: typeof Schema.String;
}>]>) => Schema.extend<Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Union<[Schema.Struct<{
b: typeof Schema.String;
}>, Schema.Struct<{
c: typeof Schema.String;
}>]>> (+1 overload)

Extends a schema with another schema.

Not all extensions are supported, and their support depends on the nature of the involved schemas.

Possible extensions include:

  • Schema.String with another Schema.String refinement or a string literal
  • Schema.Number with another Schema.Number refinement or a number literal
  • Schema.Boolean with another Schema.Boolean refinement or a boolean literal
  • A struct with another struct where overlapping fields support extension
  • A struct with in index signature
  • A struct with a union of supported schemas
  • A refinement of a struct with a supported schema
  • A suspend of a struct with a supported schema
  • A transformation between structs where the “from” and “to” sides have no overlapping fields with the target struct

@example

import * as Schema from "effect/Schema"
const schema = Schema.Struct({
a: Schema.String,
b: Schema.String
})
// const extended: Schema<
// {
// readonly a: string
// readonly b: string
// } & {
// readonly c: string
// } & {
// readonly [x: string]: string
// }
// >
const extended = Schema.asSchema(schema.pipe(
Schema.extend(Schema.Struct({ c: Schema.String })), // <= you can add more fields
Schema.extend(Schema.Record({ key: Schema.String, value: Schema.String })) // <= you can add index signatures
))

@since3.10.0

extend
(
const Struct: Schema.Struct<{
a: typeof Schema.String;
}>
Struct
,
const UnionOfStructs: Schema.Union<[Schema.Struct<{
b: typeof Schema.String;
}>, Schema.Struct<{
c: typeof Schema.String;
}>]>
UnionOfStructs
)
// ┌─── {
// | readonly a: string;
// | } & ({
// | readonly b: string;
// | } | {
// | readonly c: string;
// | })
// ▼
type
type Type = {
readonly a: string;
} & ({
readonly b: string;
} | {
readonly c: string;
})
Type
= typeof
const Extended: Schema.extend<Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Union<[Schema.Struct<{
b: typeof Schema.String;
}>, Schema.Struct<{
c: typeof Schema.String;
}>]>>
Extended
.
Schema<{ readonly a: string; } & ({ readonly b: string; } | { readonly c: string; }), { readonly a: string; } & ({ readonly b: string; } | { readonly c: string; }), never>.Type: {
readonly a: string;
} & ({
readonly b: string;
} | {
readonly c: string;
})
Type

示例(尝试使用冲突字段扩展结构)

此示例演示了尝试使用包含重叠字段名称的另一个结构扩展结构,由于类型冲突而导致错误。

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

@since3.10.0

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

@since3.10.0

String
})
const
const OverlappingUnion: Schema.Union<[Schema.Struct<{
a: typeof Schema.Number;
}>, Schema.Struct<{
d: typeof Schema.String;
}>]>
OverlappingUnion
=
import Schema
Schema
.
function Union<[Schema.Struct<{
a: typeof Schema.Number;
}>, Schema.Struct<{
d: typeof Schema.String;
}>]>(members_0: Schema.Struct<{
a: typeof Schema.Number;
}>, members_1: Schema.Struct<{
d: typeof Schema.String;
}>): Schema.Union<[Schema.Struct<{
a: typeof Schema.Number;
}>, Schema.Struct<{
d: typeof Schema.String;
}>]> (+3 overloads)

@since3.10.0

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

@since3.10.0

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

@since3.10.0

Number
}), // conflicting type for key "a"
import Schema
Schema
.
function Struct<{
d: typeof Schema.String;
}>(fields: {
d: typeof Schema.String;
}): Schema.Struct<{
d: typeof Schema.String;
}> (+1 overload)

@since3.10.0

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

@since3.10.0

String
})
)
const
const Extended: Schema.extend<Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Union<[Schema.Struct<{
a: typeof Schema.Number;
}>, Schema.Struct<{
d: typeof Schema.String;
}>]>>
Extended
=
import Schema
Schema
.
const extend: <Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Union<[Schema.Struct<{
a: typeof Schema.Number;
}>, Schema.Struct<{
d: typeof Schema.String;
}>]>>(self: Schema.Struct<{
a: typeof Schema.String;
}>, that: Schema.Union<[Schema.Struct<{
a: typeof Schema.Number;
}>, Schema.Struct<{
d: typeof Schema.String;
}>]>) => Schema.extend<Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Union<[Schema.Struct<{
a: typeof Schema.Number;
}>, Schema.Struct<{
d: typeof Schema.String;
}>]>> (+1 overload)

Extends a schema with another schema.

Not all extensions are supported, and their support depends on the nature of the involved schemas.

Possible extensions include:

  • Schema.String with another Schema.String refinement or a string literal
  • Schema.Number with another Schema.Number refinement or a number literal
  • Schema.Boolean with another Schema.Boolean refinement or a boolean literal
  • A struct with another struct where overlapping fields support extension
  • A struct with in index signature
  • A struct with a union of supported schemas
  • A refinement of a struct with a supported schema
  • A suspend of a struct with a supported schema
  • A transformation between structs where the “from” and “to” sides have no overlapping fields with the target struct

@example

import * as Schema from "effect/Schema"
const schema = Schema.Struct({
a: Schema.String,
b: Schema.String
})
// const extended: Schema<
// {
// readonly a: string
// readonly b: string
// } & {
// readonly c: string
// } & {
// readonly [x: string]: string
// }
// >
const extended = Schema.asSchema(schema.pipe(
Schema.extend(Schema.Struct({ c: Schema.String })), // <= you can add more fields
Schema.extend(Schema.Record({ key: Schema.String, value: Schema.String })) // <= you can add index signatures
))

@since3.10.0

extend
(
const Struct: Schema.Struct<{
a: typeof Schema.String;
}>
Struct
,
const OverlappingUnion: Schema.Union<[Schema.Struct<{
a: typeof Schema.Number;
}>, Schema.Struct<{
d: typeof Schema.String;
}>]>
OverlappingUnion
)
/*
throws:
Error: Unsupported schema or overlapping types
at path: ["a"]
details: cannot extend string with number
*/

示例(使用另一个细化扩展细化)

在此示例中,我们扩展了两个细化,IntegerPositive,创建了一个强制执行整数和正数约束的模式。

import {
import Schema
Schema
} from "effect"
const
const Integer: Schema.brand<typeof Schema.Int, "Int">
Integer
=
import Schema
Schema
.
class Int

@since3.10.0

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

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

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

@example

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

@since3.10.0

brand
("Int"))
const
const Positive: Schema.brand<typeof Schema.Positive, "Positive">
Positive
=
import Schema
Schema
.
class Positive

@since3.10.0

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

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

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

@example

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

@since3.10.0

brand
("Positive"))
// ┌─── Schema<number & Brand<"Positive"> & Brand<"Int">, number, never>
// ▼
const
const PositiveInteger: Schema.Schema<number & Brand<"Positive"> & Brand<"Int">, number, never>
PositiveInteger
=
import Schema
Schema
.
function asSchema<Schema.extend<Schema.brand<typeof Schema.Positive, "Positive">, Schema.brand<typeof Schema.Int, "Int">>>(schema: Schema.extend<Schema.brand<typeof Schema.Positive, "Positive">, Schema.brand<typeof Schema.Int, "Int">>): Schema.Schema<number & Brand<"Positive"> & Brand<"Int">, number, never>

@since3.10.0

asSchema
(
import Schema
Schema
.
const extend: <Schema.brand<typeof Schema.Positive, "Positive">, Schema.brand<typeof Schema.Int, "Int">>(self: Schema.brand<typeof Schema.Positive, "Positive">, that: Schema.brand<typeof Schema.Int, "Int">) => Schema.extend<Schema.brand<typeof Schema.Positive, "Positive">, Schema.brand<typeof Schema.Int, "Int">> (+1 overload)

Extends a schema with another schema.

Not all extensions are supported, and their support depends on the nature of the involved schemas.

Possible extensions include:

  • Schema.String with another Schema.String refinement or a string literal
  • Schema.Number with another Schema.Number refinement or a number literal
  • Schema.Boolean with another Schema.Boolean refinement or a boolean literal
  • A struct with another struct where overlapping fields support extension
  • A struct with in index signature
  • A struct with a union of supported schemas
  • A refinement of a struct with a supported schema
  • A suspend of a struct with a supported schema
  • A transformation between structs where the “from” and “to” sides have no overlapping fields with the target struct

@example

import * as Schema from "effect/Schema"
const schema = Schema.Struct({
a: Schema.String,
b: Schema.String
})
// const extended: Schema<
// {
// readonly a: string
// readonly b: string
// } & {
// readonly c: string
// } & {
// readonly [x: string]: string
// }
// >
const extended = Schema.asSchema(schema.pipe(
Schema.extend(Schema.Struct({ c: Schema.String })), // <= you can add more fields
Schema.extend(Schema.Record({ key: Schema.String, value: Schema.String })) // <= you can add index signatures
))

@since3.10.0

extend
(
const Positive: Schema.brand<typeof Schema.Positive, "Positive">
Positive
,
const Integer: Schema.brand<typeof Schema.Int, "Int">
Integer
))
import Schema
Schema
.
decodeUnknownSync<number & Brand<"Positive"> & Brand<"Int">, number>(schema: Schema.Schema<number & Brand<"Positive"> & Brand<"Int">, number, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => number & Brand<"Positive"> & Brand<"Int">
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const PositiveInteger: Schema.Schema<number & Brand<"Positive"> & Brand<"Int">, number, never>
PositiveInteger
)(-1)
/*
throws
ParseError: positive & Brand<"Positive"> & int & Brand<"Int">
└─ From side refinement failure
└─ positive & Brand<"Positive">
└─ Predicate refinement failure
└─ Expected a positive number, actual -1
*/
import Schema
Schema
.
decodeUnknownSync<number & Brand<"Positive"> & Brand<"Int">, number>(schema: Schema.Schema<number & Brand<"Positive"> & Brand<"Int">, number, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => number & Brand<"Positive"> & Brand<"Int">
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const PositiveInteger: Schema.Schema<number & Brand<"Positive"> & Brand<"Int">, number, never>
PositiveInteger
)(1.1)
/*
throws
ParseError: positive & Brand<"Positive"> & int & Brand<"Int">
└─ Predicate refinement failure
└─ Expected an integer, actual 1.1
*/

要在模式创建期间直接重命名属性,您可以使用Schema.fromKey函数。

示例(重命名必需属性)

import {
import Schema
Schema
} from "effect"
const
const schema: Schema.Struct<{
a: Schema.PropertySignature<":", string, "c", ":", string, false, never>;
b: typeof Schema.Number;
}>
schema
=
import Schema
Schema
.
function Struct<{
a: Schema.PropertySignature<":", string, "c", ":", string, false, never>;
b: typeof Schema.Number;
}>(fields: {
a: Schema.PropertySignature<":", string, "c", ":", string, false, never>;
b: typeof Schema.Number;
}): Schema.Struct<{
a: Schema.PropertySignature<":", string, "c", ":", string, false, never>;
b: typeof Schema.Number;
}> (+1 overload)

@since3.10.0

Struct
({
a: Schema.PropertySignature<":", string, "c", ":", string, false, never>
a
:
import Schema
Schema
.
const propertySignature: <typeof Schema.String>(self: typeof Schema.String) => Schema.propertySignature<typeof Schema.String>

Lifts a Schema into a PropertySignature.

@since3.10.0

propertySignature
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
).
Pipeable.pipe<Schema.propertySignature<typeof Schema.String>, Schema.PropertySignature<":", string, "c", ":", string, false, never>>(this: Schema.propertySignature<typeof Schema.String>, ab: (_: Schema.propertySignature<typeof Schema.String>) => Schema.PropertySignature<":", string, "c", ":", string, false, never>): Schema.PropertySignature<":", string, "c", ":", string, false, never> (+21 overloads)
pipe
(
import Schema
Schema
.
const fromKey: <"c">(key: "c") => <TypeToken, Type, EncodedToken, Encoded, HasDefault, R>(self: Schema.PropertySignature<TypeToken, Type, PropertyKey, EncodedToken, Encoded, HasDefault, R>) => Schema.PropertySignature<TypeToken, Type, "c", EncodedToken, Encoded, HasDefault, R> (+1 overload)

Enhances a property signature by specifying a different key for it in the Encoded type.

@since3.10.0

fromKey
("c")),
b: typeof Schema.Number
b
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
// ┌─── { readonly c: string; readonly b: number; }
// ▼
type
type Encoded = {
readonly c: string;
readonly b: number;
}
Encoded
= typeof
const schema: Schema.Struct<{
a: Schema.PropertySignature<":", string, "c", ":", string, false, never>;
b: typeof Schema.Number;
}>
schema
.
Schema<{ readonly a: string; readonly b: number; }, { readonly c: string; readonly b: number; }, never>.Encoded: {
readonly c: string;
readonly b: number;
}
Encoded
// ┌─── { readonly a: string; readonly b: number; }
// ▼
type
type Type = {
readonly a: string;
readonly b: number;
}
Type
= typeof
const schema: Schema.Struct<{
a: Schema.PropertySignature<":", string, "c", ":", string, false, never>;
b: typeof Schema.Number;
}>
schema
.
Schema<{ readonly a: string; readonly b: number; }, { readonly c: string; readonly b: number; }, never>.Type: {
readonly a: string;
readonly b: number;
}
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Struct<{
a: Schema.PropertySignature<":", string, "c", ":", string, false, never>;
b: typeof Schema.Number;
}>
schema
)({
c: string
c
: "c",
b: number
b
: 1 }))
// Output: { a: "c", b: 1 }

示例(重命名可选属性)

import {
import Schema
Schema
} from "effect"
const
const schema: Schema.Struct<{
a: Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>;
b: typeof Schema.Number;
}>
schema
=
import Schema
Schema
.
function Struct<{
a: Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>;
b: typeof Schema.Number;
}>(fields: {
a: Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>;
b: typeof Schema.Number;
}): Schema.Struct<{
a: Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>;
b: typeof Schema.Number;
}> (+1 overload)

@since3.10.0

Struct
({
a: Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>
a
:
import Schema
Schema
.
const optional: <typeof Schema.String>(self: typeof Schema.String) => Schema.optional<typeof Schema.String>

@since3.10.0

optional
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
).
Pipeable.pipe<Schema.optional<typeof Schema.String>, Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>>(this: Schema.optional<typeof Schema.String>, ab: (_: Schema.optional<typeof Schema.String>) => Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>): Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never> (+21 overloads)
pipe
(
import Schema
Schema
.
const fromKey: <"c">(key: "c") => <TypeToken, Type, EncodedToken, Encoded, HasDefault, R>(self: Schema.PropertySignature<TypeToken, Type, PropertyKey, EncodedToken, Encoded, HasDefault, R>) => Schema.PropertySignature<TypeToken, Type, "c", EncodedToken, Encoded, HasDefault, R> (+1 overload)

Enhances a property signature by specifying a different key for it in the Encoded type.

@since3.10.0

fromKey
("c")),
b: typeof Schema.Number
b
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
// ┌─── { readonly b: number; readonly c?: string | undefined; }
// ▼
type
type Encoded = {
readonly b: number;
readonly c?: string | undefined;
}
Encoded
= typeof
const schema: Schema.Struct<{
a: Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>;
b: typeof Schema.Number;
}>
schema
.
Schema<{ readonly a?: string | undefined; readonly b: number; }, { readonly b: number; readonly c?: string | undefined; }, never>.Encoded: {
readonly b: number;
readonly c?: string | undefined;
}
Encoded
// ┌─── { readonly a?: string | undefined; readonly b: number; }
// ▼
type
type Type = {
readonly a?: string | undefined;
readonly b: number;
}
Type
= typeof
const schema: Schema.Struct<{
a: Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>;
b: typeof Schema.Number;
}>
schema
.
Schema<{ readonly a?: string | undefined; readonly b: number; }, { readonly b: number; readonly c?: string | undefined; }, never>.Type: {
readonly a?: string | undefined;
readonly b: number;
}
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Struct<{
a: Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>;
b: typeof Schema.Number;
}>
schema
)({
c: string
c
: "c",
b: number
b
: 1 }))
// Output: { a: 'c', b: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Struct<{
a: Schema.PropertySignature<"?:", string | undefined, "c", "?:", string | undefined, false, never>;
b: typeof Schema.Number;
}>
schema
)({
b: number
b
: 1 }))
// Output: { b: 1 }

使用Schema.optional会自动返回PropertySignature,因此不需要像前面示例中重命名必需字段那样显式使用Schema.propertySignature

对于现有模式,Schema.rename API提供了一种在模式中系统地更改属性名称的方法,即使在联合等复杂结构中也是如此,尽管在结构的情况下您会丢失原始字段类型。

示例(重命名结构模式中的属性)

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

@since3.10.0

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

@since3.10.0

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

@since3.10.0

Number
})
// Renaming the "c" property to "a"
//
//
// ┌─── SchemaClass<{
// | readonly a: string;
// | readonly b: number;
// | }>
// ▼
const
const Renamed: Schema.SchemaClass<{
readonly a: string;
readonly b: number;
}, {
readonly c: string;
readonly b: number;
}, never>
Renamed
=
import Schema
Schema
.
const rename: <{
readonly c: string;
readonly b: number;
}, {
readonly c: string;
readonly b: number;
}, never, {
readonly c: "a";
}>(self: Schema.Schema<{
readonly c: string;
readonly b: number;
}, {
readonly c: string;
readonly b: number;
}, never>, mapping: {
readonly c: "a";
}) => Schema.SchemaClass<{
readonly a: string;
readonly b: number;
}, {
readonly c: string;
readonly b: number;
}, never> (+1 overload)

@since3.10.0

rename
(
const Original: Schema.Struct<{
c: typeof Schema.String;
b: typeof Schema.Number;
}>
Original
, {
c: "a"
c
: "a" })
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Renamed: Schema.SchemaClass<{
readonly a: string;
readonly b: number;
}, {
readonly c: string;
readonly b: number;
}, never>
Renamed
)({
c: string
c
: "c",
b: number
b
: 1 }))
// Output: { a: "c", b: 1 }

示例(重命名联合模式中的属性)

import {
import Schema
Schema
} from "effect"
const
const Original: Schema.Union<[Schema.Struct<{
c: typeof Schema.String;
b: typeof Schema.Number;
}>, Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.Boolean;
}>]>
Original
=
import Schema
Schema
.
function Union<[Schema.Struct<{
c: typeof Schema.String;
b: typeof Schema.Number;
}>, Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.Boolean;
}>]>(members_0: Schema.Struct<{
c: typeof Schema.String;
b: typeof Schema.Number;
}>, members_1: Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.Boolean;
}>): Schema.Union<[Schema.Struct<{
c: typeof Schema.String;
b: typeof Schema.Number;
}>, Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.Boolean;
}>]> (+3 overloads)

@since3.10.0

Union
(
import Schema
Schema
.
function Struct<{
c: typeof Schema.String;
b: typeof Schema.Number;
}>(fields: {
c: typeof Schema.String;
b: typeof Schema.Number;
}): Schema.Struct<{
c: typeof Schema.String;
b: typeof Schema.Number;
}> (+1 overload)

@since3.10.0

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

@since3.10.0

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

@since3.10.0

Number
}),
import Schema
Schema
.
function Struct<{
c: typeof Schema.String;
d: typeof Schema.Boolean;
}>(fields: {
c: typeof Schema.String;
d: typeof Schema.Boolean;
}): Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.Boolean;
}> (+1 overload)

@since3.10.0

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

@since3.10.0

String
,
d: typeof Schema.Boolean
d
:
import Schema
Schema
.
class Boolean
export Boolean

@since3.10.0

Boolean
})
)
// 为所有成员将"c"属性重命名为"a"
//
// ┌─── SchemaClass<{
// | readonly a: string;
// | readonly b: number;
// | } | {
// | readonly a: string;
// | readonly d: number;
// | }>
// ▼
const
const Renamed: Schema.SchemaClass<{
readonly a: string;
readonly b: number;
} | {
readonly a: string;
readonly d: boolean;
}, {
readonly c: string;
readonly b: number;
} | {
readonly c: string;
readonly d: boolean;
}, never>
Renamed
=
import Schema
Schema
.
const rename: <{
readonly c: string;
readonly b: number;
} | {
readonly c: string;
readonly d: boolean;
}, {
readonly c: string;
readonly b: number;
} | {
readonly c: string;
readonly d: boolean;
}, never, {
readonly c: "a";
}>(self: Schema.Schema<{
readonly c: string;
readonly b: number;
} | {
readonly c: string;
readonly d: boolean;
}, {
readonly c: string;
readonly b: number;
} | {
readonly c: string;
readonly d: boolean;
}, never>, mapping: {
readonly c: "a";
}) => Schema.SchemaClass<{
readonly a: string;
readonly b: number;
} | {
readonly a: string;
readonly d: boolean;
}, {
readonly c: string;
readonly b: number;
} | {
readonly c: string;
readonly d: boolean;
}, never> (+1 overload)

@since3.10.0

rename
(
const Original: Schema.Union<[Schema.Struct<{
c: typeof Schema.String;
b: typeof Schema.Number;
}>, Schema.Struct<{
c: typeof Schema.String;
d: typeof Schema.Boolean;
}>]>
Original
, {
c: "a"
c
: "a" })
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Renamed: Schema.SchemaClass<{
readonly a: string;
readonly b: number;
} | {
readonly a: string;
readonly d: boolean;
}, {
readonly c: string;
readonly b: number;
} | {
readonly c: string;
readonly d: boolean;
}, never>
Renamed
)({
c: string
c
: "c",
b: number
b
: 1 }))
// Output: { a: "c", b: 1 }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

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

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Renamed: Schema.SchemaClass<{
readonly a: string;
readonly b: number;
} | {
readonly a: string;
readonly d: boolean;
}, {
readonly c: string;
readonly b: number;
} | {
readonly c: string;
readonly d: boolean;
}, never>
Renamed
)({
c: string
c
: "c",
d: boolean
d
: false }))
// Output: { a: 'c', d: false }

Schema.suspend函数专为定义引用自身的模式而设计,例如在递归数据结构中。

示例(自引用模式)

在此示例中,Category模式通过subcategories字段引用自身,该字段是Category对象的数组。

import {
import Schema
Schema
} from "effect"
interface
interface Category
Category
{
readonly
Category.name: string
name
: string
readonly
Category.subcategories: readonly Category[]
subcategories
:
interface ReadonlyArray<T>
ReadonlyArray
<
interface Category
Category
>
}
const
const Category: Schema.Struct<{
name: typeof Schema.String;
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
}>
Category
=
import Schema
Schema
.
function Struct<{
name: typeof Schema.String;
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
}>(fields: {
name: typeof Schema.String;
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
}): Schema.Struct<{
name: typeof Schema.String;
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
}> (+1 overload)

@since3.10.0

Struct
({
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
<
interface Category
Category
> =>
const Category: Schema.Struct<{
name: typeof Schema.String;
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
}>
Category
)
)
})

示例(类型推断错误)

import {
import Schema
Schema
} from "effect"
const Category =
import Schema
Schema
.
function Struct<{
name: typeof Schema.String;
subcategories: Schema.Array$<Schema.suspend<unknown, unknown, unknown>>;
}>(fields: {
name: typeof Schema.String;
subcategories: Schema.Array$<Schema.suspend<unknown, unknown, unknown>>;
}): Schema.Struct<{
name: typeof Schema.String;
subcategories: Schema.Array$<Schema.suspend<unknown, unknown, unknown>>;
}> (+1 overload)

@since3.10.0

Struct
({
Error ts(7022) ― 'Category' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.
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
(() =>
const Category: any
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.
})

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

示例(分离递归字段)

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

@since3.10.0

String
// ...other fields as needed
}
// 为Category模式定义接口,
// 扩展已定义字段的Type
interface
interface Category
Category
extends
import Schema
Schema
.
namespace Struct

@since3.10.0

@since3.10.0

@since3.10.0

Struct
.
type Struct<Fields extends Struct.Fields>.Type<F extends Schema.Struct.Fields> = UnionToIntersection<{ [K in keyof F]: F[K] extends Schema.Struct.OptionalTypePropertySignature ? { readonly [H in K]?: Schema.Schema.Type<F[H]>; } : { readonly [h in K]: Schema.Schema.Type<F[h]>; }; }[keyof F]> extends infer Q ? Q : never

@since3.10.0

Type
<typeof
const fields: {
name: typeof Schema.String;
}
fields
> {
// 使用递归定义`subcategories`
readonly
Category.subcategories: readonly Category[]
subcategories
:
interface ReadonlyArray<T>
ReadonlyArray
<
interface Category
Category
>
}
const
const Category: Schema.Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
name: typeof Schema.String;
}>
Category
=
import Schema
Schema
.
function Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
name: typeof Schema.String;
}>(fields: {
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
name: typeof Schema.String;
}): Schema.Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
name: typeof Schema.String;
}> (+1 overload)

@since3.10.0

Struct
({
...
const fields: {
name: typeof Schema.String;
}
fields
, // 展开基础字段
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
(
// 使用递归定义`subcategories`
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
<
interface Category
Category
> =>
const Category: Schema.Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
name: typeof Schema.String;
}>
Category
)
)
})

您还可以使用Schema.suspend创建互相递归模式,其中两个模式相互引用。在以下示例中,ExpressionOperation通过相互引用形成简单的算术表达式树。

示例(定义互相递归模式)

import {
import Schema
Schema
} from "effect"
interface
interface Expression
Expression
{
readonly
Expression.type: "expression"
type
: "expression"
readonly
Expression.value: number | Operation
value
: number |
interface Operation
Operation
}
interface
interface Operation
Operation
{
readonly
Operation.type: "operation"
type
: "operation"
readonly
Operation.operator: "+" | "-"
operator
: "+" | "-"
readonly
Operation.left: Expression
left
:
interface Expression
Expression
readonly
Operation.right: Expression
right
:
interface Expression
Expression
}
const
const Expression: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>
Expression
=
import Schema
Schema
.
function Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>(fields: {
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}): Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}> (+1 overload)

@since3.10.0

Struct
({
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
<
interface Operation
Operation
> =>
const Operation: Schema.Struct<{
type: Schema.Literal<["operation"]>;
operator: Schema.Literal<["+", "-"]>;
left: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>;
right: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>;
}>
Operation
)
)
})
const
const Operation: Schema.Struct<{
type: Schema.Literal<["operation"]>;
operator: Schema.Literal<["+", "-"]>;
left: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>;
right: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>;
}>
Operation
=
import Schema
Schema
.
function Struct<{
type: Schema.Literal<["operation"]>;
operator: Schema.Literal<["+", "-"]>;
left: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>;
right: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>;
}>(fields: {
type: Schema.Literal<["operation"]>;
operator: Schema.Literal<["+", "-"]>;
left: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>;
right: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>;
}): Schema.Struct<...> (+1 overload)

@since3.10.0

Struct
({
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: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>
left
:
const Expression: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>
Expression
,
right: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>
right
:
const Expression: Schema.Struct<{
type: Schema.Literal<["expression"]>;
value: Schema.Union<[typeof Schema.Number, Schema.suspend<Operation, Operation, never>]>;
}>
Expression
})

定义Encoded类型与Type类型不同的递归模式会增加另一层复杂性。在这种情况下,我们需要定义两个接口:一个用于Type类型(如前所见),另一个用于Encoded类型。

示例(具有不同编码和类型定义的递归模式)

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

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 Category
Category
extends
import Schema
Schema
.
namespace Struct

@since3.10.0

@since3.10.0

@since3.10.0

Struct
.
type Struct<Fields extends Struct.Fields>.Type<F extends Schema.Struct.Fields> = UnionToIntersection<{ [K in keyof F]: F[K] extends Schema.Struct.OptionalTypePropertySignature ? { readonly [H in K]?: Schema.Schema.Type<F[H]>; } : { readonly [h in K]: Schema.Schema.Type<F[h]>; }; }[keyof F]> extends infer Q ? Q : never

@since3.10.0

Type
<typeof
const fields: {
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}
fields
> {
readonly
Category.subcategories: readonly Category[]
subcategories
:
interface ReadonlyArray<T>
ReadonlyArray
<
interface Category
Category
>
}
const
const Category: Schema.Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}>
Category
=
import Schema
Schema
.
function Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}>(fields: {
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}): Schema.Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, Category, never>>;
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}> (+1 overload)

@since3.10.0

Struct
({
...
const fields: {
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}
fields
,
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
<
interface Category
Category
> => Category)
Error ts(2322) ― Type 'Struct<{ subcategories: Array$<suspend<Category, Category, never>>; id: typeof NumberFromString; name: typeof String$; }>' 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'.
)
})

此错误发生是因为显式注解Schema.Schema<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 Category
Category
extends
import Schema
Schema
.
namespace Struct

@since3.10.0

@since3.10.0

@since3.10.0

Struct
.
type Struct<Fields extends Struct.Fields>.Type<F extends Schema.Struct.Fields> = UnionToIntersection<{ [K in keyof F]: F[K] extends Schema.Struct.OptionalTypePropertySignature ? { readonly [H in K]?: Schema.Schema.Type<F[H]>; } : { readonly [h in K]: Schema.Schema.Type<F[h]>; }; }[keyof F]> extends infer Q ? Q : never

@since3.10.0

Type
<typeof
const fields: {
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}
fields
> {
readonly
Category.subcategories: readonly Category[]
subcategories
:
interface ReadonlyArray<T>
ReadonlyArray
<
interface Category
Category
>
}
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
> {
readonly
CategoryEncoded.subcategories: readonly CategoryEncoded[]
subcategories
:
interface ReadonlyArray<T>
ReadonlyArray
<
interface CategoryEncoded
CategoryEncoded
>
}
const
const Category: Schema.Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, CategoryEncoded, never>>;
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}>
Category
=
import Schema
Schema
.
function Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, CategoryEncoded, never>>;
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}>(fields: {
subcategories: Schema.Array$<Schema.suspend<Category, CategoryEncoded, never>>;
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}): Schema.Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, CategoryEncoded, never>>;
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}> (+1 overload)

@since3.10.0

Struct
({
...
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
(
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
<
interface Category
Category
,
interface CategoryEncoded
CategoryEncoded
> =>
const Category: Schema.Struct<{
subcategories: Schema.Array$<Schema.suspend<Category, CategoryEncoded, never>>;
id: typeof Schema.NumberFromString;
name: typeof Schema.String;
}>
Category
)
)
})