Skip to content

Schema 注解

Schema 设计的关键特性之一是其灵活性和可定制能力。 这是通过”注解”实现的。 模式的 ast 字段中的每个节点都有一个 annotations: Record<string | symbol, unknown> 字段, 它允许您向模式附加额外信息。 您可以使用 annotations 方法或 Schema.annotations API 来管理这些注解。

示例(使用注解自定义模式)

import {
import Schema
Schema
} from "effect"
// 定义一个 Password 模式,从字符串类型开始
const
const Password: Schema.refine<string, Schema.filter<Schema.SchemaClass<string, string, never>>>
Password
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
// 为非字符串值添加自定义错误消息
.
Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.SchemaClass<string, string, never>

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

annotations
({
Annotations.Schema<string, readonly []>.message?: MessageAnnotation
message
: () => "not a string" })
.
Pipeable.pipe<Schema.SchemaClass<string, string, never>, Schema.filter<Schema.SchemaClass<string, string, never>>, Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>>(this: Schema.SchemaClass<...>, ab: (_: Schema.SchemaClass<string, string, never>) => Schema.filter<Schema.SchemaClass<string, string, never>>, bc: (_: Schema.filter<Schema.SchemaClass<string, string, never>>) => Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>): Schema.filter<...> (+21 overloads)
pipe
(
// 强制非空字符串并提供自定义错误消息
import Schema
Schema
.
const nonEmptyString: <Schema.SchemaClass<string, string, never>>(annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: Schema.SchemaClass<string, string, never> & Schema.Schema<A, string, never>) => Schema.filter<Schema.SchemaClass<string, string, never>>

@since3.10.0

nonEmptyString
({
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "required" }),
// 将字符串长度限制为 10 个字符或更少
// 并为超出长度提供自定义错误消息
import Schema
Schema
.
const maxLength: <Schema.filter<Schema.SchemaClass<string, string, never>>>(maxLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <A>(self: Schema.filter<Schema.SchemaClass<string, string, never>> & Schema.Schema<A, string, never>) => Schema.filter<Schema.filter<Schema.SchemaClass<string, string, never>>>

@since3.10.0

maxLength
(10, {
Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: (
issue: ParseIssue
issue
) => `${
issue: ParseIssue
issue
.
actual: unknown

@since3.10.0

actual
} is too long`
})
)
.
Annotable<refine<string, filter<SchemaClass<string, string, never>>>, string, string, never>.annotations(annotations: Schema.Annotations.GenericSchema<string>): Schema.refine<string, Schema.filter<Schema.SchemaClass<string, string, never>>>

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

annotations
({
// 为模式添加唯一标识符
Annotations.Schema<string, readonly []>.identifier?: string
identifier
: "Password",
// 为模式提供标题
Annotations.Doc<string>.title?: string
title
: "password",
// 包含解释此模式代表什么的描述
Annotations.Doc<string>.description?: string
description
:
"A password is a secret string used to authenticate a user",
// 添加示例以提高清晰度
Annotations.Doc<string>.examples?: readonly [string, ...string[]]
examples
: ["1Ki77y", "jelly22fi$h"],
// 包含任何额外的文档
Annotations.Doc<string>.documentation?: string
documentation
: `...technical information on Password schema...`
})

下表提供了常见内置注解及其用途的概述:

注解描述
identifier为模式分配唯一标识符,适用于 TypeScript 标识符和代码生成目的。通常在 TreeFormatter 等工具中使用以澄清输出。示例包括 "Person""Product"
title为模式设置简短的描述性标题,类似于 JSON Schema 标题。对文档或 UI 标题很有用。它也被 TreeFormatter 用来增强错误消息的可读性。
description提供关于模式目的的详细解释,类似于 JSON Schema 描述。被 TreeFormatter 用来提供更详细的错误消息。
documentation为模式扩展详细文档,对开发人员或自动文档生成有益。
examples列出有效模式值的示例,类似于 JSON Schema 中的示例属性,对文档和验证测试很有用。
default为模式定义默认值,类似于 JSON Schema 中的默认属性,以确保模式在适用的地方预先填充。
message自定义验证失败的错误消息,在解码或验证错误期间改善 TreeFormatterArrayFormatter 等工具输出的清晰度。
jsonSchema指定影响 JSON Schema 文档生成的注解,自定义模式的表示方式。
arbitrary配置生成 Arbitrary 测试数据的设置。
pretty配置生成 Pretty 输出的设置。
equivalence配置评估数据 Equivalence 的设置。
concurrency控制并发行为,确保模式在并发操作下表现最佳。有关详细用法,请参阅并发注解
batching管理批处理操作的设置,以在可以分组操作时提高性能。
parseIssueTitle为解析问题提供自定义标题,增强 TreeFormatter 输出中的错误描述。有关更多信息,请参阅 ParseIssueTitle 注解
parseOptions允许在模式级别覆盖解析选项,提供对解析行为的精细控制。有关应用详细信息,请参阅在模式级别自定义解析行为
decodingFallback提供一种定义自定义回退行为的方法,当解码操作失败时触发。有关详细用法,请参阅使用回退处理解码错误

For more complex schemas like Struct, Array, or Union that contain multiple nested schemas, the concurrency annotation provides a way to control how validations are executed concurrently.

type ConcurrencyAnnotation = number | "unbounded" | "inherit" | undefined

Here’s a shorter version presented in a table:

ValueDescription
numberLimits the maximum number of concurrent tasks.
"unbounded"All tasks run concurrently with no limit.
"inherit"Inherits concurrency settings from the parent context.
undefinedTasks run sequentially, one after the other (default behavior).

Example (Sequential Execution)

In this example, we define three tasks that simulate asynchronous operations with different durations. Since no concurrency is specified, the tasks are executed sequentially, one after the other.

import {
import Schema
Schema
} from "effect"
import type {
import Duration
Duration
} from "effect"
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Simulates an async task
const
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
= (
id: number
id
: number,
duration: Duration.DurationInput
duration
:
import Duration
Duration
.
type DurationInput = number | bigint | Duration.Duration | readonly [seconds: number, nanos: number] | `${number} nano` | `${number} nanos` | `${number} micro` | `${number} micros` | `${number} milli` | `${number} millis` | `${number} second` | `${number} seconds` | `${number} minute` | `${number} minutes` | `${number} hour` | `${number} hours` | `${number} day` | `${number} days` | `${number} week` | `${number} weeks`

@since2.0.0

DurationInput
) =>
import Schema
Schema
.
class String
export String

@since3.10.0

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

@since3.10.0

filterEffect
(() =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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

When to Use

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

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

Example

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

@since2.0.0

gen
(function* () {
yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const sleep: (duration: Duration.DurationInput) => Effect.Effect<void>

Suspends the execution of an effect for a specified Duration.

Details

This function pauses the execution of an effect for a given duration. It is asynchronous, meaning that it does not block the fiber executing the effect. Instead, the fiber is suspended during the delay period and can resume once the specified time has passed.

The duration can be specified using various formats supported by the Duration module, such as a string ("2 seconds") or numeric value representing milliseconds.

Example

import { Effect } from "effect"
const program = Effect.gen(function*() {
console.log("Starting task...")
yield* Effect.sleep("3 seconds") // Waits for 3 seconds
console.log("Task completed!")
})
Effect.runFork(program)
// Output:
// Starting task...
// Task completed!

@since2.0.0

sleep
(
duration: Duration.DurationInput
duration
)
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
(`Task ${
id: number
id
} done`)
return true
})
)
)
const
const Sequential: Schema.Tuple<[Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>]>
Sequential
=
import Schema
Schema
.
function Tuple<[Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>]>(elements_0: Schema.filterEffect<typeof Schema.String, never>, elements_1: Schema.filterEffect<typeof Schema.String, never>, elements_2: Schema.filterEffect<typeof Schema.String, never>): Schema.Tuple<[Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<...>]> (+2 overloads)

@since3.10.0

Tuple
(
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(1, "30 millis"),
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(2, "10 millis"),
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(3, "20 millis")
)
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

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

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

When to Use

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

Example (Running a Successful Effect as a Promise)

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

Example (Handling a Failing Effect as a Rejected Promise)

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

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

@since2.0.0

runPromise
(
import Schema
Schema
.
const decode: <readonly [string, string, string], readonly [string, string, string], never>(schema: Schema.Schema<readonly [string, string, string], readonly [string, string, string], never>, options?: ParseOptions) => (i: readonly [string, string, string], overrideOptions?: ParseOptions) => Effect.Effect<readonly [string, string, string], ParseError, never>

@since3.10.0

decode
(
const Sequential: Schema.Tuple<[Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>]>
Sequential
)(["a", "b", "c"]))
/*
Output:
Task 1 done
Task 2 done
Task 3 done
*/

Example (Concurrent Execution)

By adding a concurrency annotation set to "unbounded", the tasks can now run concurrently, meaning they don’t wait for one another to finish before starting. This allows faster execution when multiple tasks are involved.

import {
import Schema
Schema
} from "effect"
import type {
import Duration
Duration
} from "effect"
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Simulates an async task
const
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
= (
id: number
id
: number,
duration: Duration.DurationInput
duration
:
import Duration
Duration
.
type DurationInput = number | bigint | Duration.Duration | readonly [seconds: number, nanos: number] | `${number} nano` | `${number} nanos` | `${number} micro` | `${number} micros` | `${number} milli` | `${number} millis` | `${number} second` | `${number} seconds` | `${number} minute` | `${number} minutes` | `${number} hour` | `${number} hours` | `${number} day` | `${number} days` | `${number} week` | `${number} weeks`

@since2.0.0

DurationInput
) =>
import Schema
Schema
.
class String
export String

@since3.10.0

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

@since3.10.0

filterEffect
(() =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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

When to Use

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

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

Example

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

@since2.0.0

gen
(function* () {
yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const sleep: (duration: Duration.DurationInput) => Effect.Effect<void>

Suspends the execution of an effect for a specified Duration.

Details

This function pauses the execution of an effect for a given duration. It is asynchronous, meaning that it does not block the fiber executing the effect. Instead, the fiber is suspended during the delay period and can resume once the specified time has passed.

The duration can be specified using various formats supported by the Duration module, such as a string ("2 seconds") or numeric value representing milliseconds.

Example

import { Effect } from "effect"
const program = Effect.gen(function*() {
console.log("Starting task...")
yield* Effect.sleep("3 seconds") // Waits for 3 seconds
console.log("Task completed!")
})
Effect.runFork(program)
// Output:
// Starting task...
// Task completed!

@since2.0.0

sleep
(
duration: Duration.DurationInput
duration
)
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
(`Task ${
id: number
id
} done`)
return true
})
)
)
const
const Concurrent: Schema.Tuple<[Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>]>
Concurrent
=
import Schema
Schema
.
function Tuple<[Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>]>(elements_0: Schema.filterEffect<typeof Schema.String, never>, elements_1: Schema.filterEffect<typeof Schema.String, never>, elements_2: Schema.filterEffect<typeof Schema.String, never>): Schema.Tuple<[Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<...>]> (+2 overloads)

@since3.10.0

Tuple
(
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(1, "30 millis"),
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(2, "10 millis"),
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(3, "20 millis")
).
Tuple<[filterEffect<typeof String$, never>, filterEffect<typeof String$, never>, filterEffect<typeof String$, never>]>.annotations(annotations: Schema.Annotations.Schema<readonly [string, string, string], readonly []>): Schema.Tuple<[Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>]>

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

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

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

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

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

When to Use

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

Example (Running a Successful Effect as a Promise)

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

Example (Handling a Failing Effect as a Rejected Promise)

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

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

@since2.0.0

runPromise
(
import Schema
Schema
.
const decode: <readonly [string, string, string], readonly [string, string, string], never>(schema: Schema.Schema<readonly [string, string, string], readonly [string, string, string], never>, options?: ParseOptions) => (i: readonly [string, string, string], overrideOptions?: ParseOptions) => Effect.Effect<readonly [string, string, string], ParseError, never>

@since3.10.0

decode
(
const Concurrent: Schema.Tuple<[Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>, Schema.filterEffect<typeof Schema.String, never>]>
Concurrent
)(["a", "b", "c"]))
/*
Output:
Task 2 done
Task 3 done
Task 1 done
*/

The DecodingFallbackAnnotation allows you to handle decoding errors by providing a custom fallback logic.

type DecodingFallbackAnnotation<A> = (
issue: ParseIssue
) => Effect<A, ParseIssue>

This annotation enables you to specify fallback behavior when decoding fails, making it possible to recover gracefully from errors.

Example (Basic Fallback)

In this basic example, when decoding fails (e.g., the input is null), the fallback value is returned instead of an error.

import {
import Schema
Schema
} from "effect"
import {
import Either

@since2.0.0

@since2.0.0

Either
} from "effect"
// Schema with a fallback value
const
const schema: Schema.SchemaClass<string, string, never>
schema
=
import Schema
Schema
.
class String
export String

@since3.10.0

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

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

annotations
({
Annotations.Schema<string, readonly []>.decodingFallback?: DecodingFallbackAnnotation<string>
decodingFallback
: () =>
import Either

@since2.0.0

@since2.0.0

Either
.
const right: <string>(right: string) => Either.Either<string, never>

Constructs a new Either holding a Right value. This usually represents a successful value due to the right bias of this structure.

@since2.0.0

right
("<fallback>")
})
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<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.SchemaClass<string, string, never>
schema
)("valid input"))
// Output: valid input
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<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.SchemaClass<string, string, never>
schema
)(null))
// Output: <fallback>

Example (Advanced Fallback with Logging)

In this advanced example, when a decoding error occurs, the schema logs the issue and then returns a fallback value. This demonstrates how you can incorporate logging and other side effects during error handling.

import {
import Schema
Schema
} from "effect"
import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
} from "effect"
// Schema with logging and fallback
const
const schemaWithLog: Schema.SchemaClass<string, string, never>
schemaWithLog
=
import Schema
Schema
.
class String
export String

@since3.10.0

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

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

annotations
({
Annotations.Schema<string, readonly []>.decodingFallback?: DecodingFallbackAnnotation<string>
decodingFallback
: (
issue: ParseIssue
issue
) =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

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

When to Use

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

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

Example

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

@since2.0.0

gen
(function* () {
// Log the error issue
yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>

Logs one or more messages or error causes at the current log level.

Details

This function provides a simple way to log messages or error causes during the execution of your effects. By default, logs are recorded at the INFO level, but this can be adjusted using other logging utilities (Logger.withMinimumLogLevel). Multiple items, including Cause instances, can be logged in a single call. When logging Cause instances, detailed error information is included in the log output.

The log output includes useful metadata like the current timestamp, log level, and fiber ID, making it suitable for debugging and tracking purposes. This function does not interrupt or alter the effect's execution flow.

Example

import { Cause, Effect } from "effect"
const program = Effect.log(
"message1",
"message2",
Cause.die("Oh no!"),
Cause.die("Oh uh!")
)
Effect.runFork(program)
// Output:
// timestamp=... level=INFO fiber=#0 message=message1 message=message2 cause="Error: Oh no!
// Error: Oh uh!"

@since2.0.0

log
(
issue: ParseIssue
issue
.
_tag: "Type" | "Missing" | "Unexpected" | "Forbidden" | "Pointer" | "Refinement" | "Transformation" | "Composite"

@since3.10.0

@since3.10.0

@since3.10.0

@since3.10.0

@since3.10.0

@since3.10.0

@since3.10.0

@since3.10.0

_tag
)
// Simulate a delay
yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const sleep: (duration: DurationInput) => Effect.Effect<void>

Suspends the execution of an effect for a specified Duration.

Details

This function pauses the execution of an effect for a given duration. It is asynchronous, meaning that it does not block the fiber executing the effect. Instead, the fiber is suspended during the delay period and can resume once the specified time has passed.

The duration can be specified using various formats supported by the Duration module, such as a string ("2 seconds") or numeric value representing milliseconds.

Example

import { Effect } from "effect"
const program = Effect.gen(function*() {
console.log("Starting task...")
yield* Effect.sleep("3 seconds") // Waits for 3 seconds
console.log("Task completed!")
})
Effect.runFork(program)
// Output:
// Starting task...
// Task completed!

@since2.0.0

sleep
(10)
// Return a fallback value
return yield*
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Creates an Effect that always succeeds with a given value.

When to Use

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

Example (Creating a Successful Effect)

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

@seefail to create an effect that represents a failure.

@since2.0.0

succeed
("<fallback>")
})
})
// Run the effectful fallback logic
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

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

Executes an effect and returns the result as a Promise.

Details

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

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

When to Use

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

Example (Running a Successful Effect as a Promise)

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

Example (Handling a Failing Effect as a Rejected Promise)

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

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

@since2.0.0

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

@since3.10.0

decodeUnknown
(
const schemaWithLog: Schema.SchemaClass<string, string, never>
schemaWithLog
)(null)).
Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<void>

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

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

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

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

then
(
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
)
/*
Output:
timestamp=2024-07-25T13:22:37.706Z level=INFO fiber=#0 message=Type
<fallback>
*/

In addition to built-in annotations, you can define custom annotations to meet specific requirements. For instance, here’s how to create a deprecated annotation:

Example (Defining a Custom Annotation)

import {
import Schema
Schema
} from "effect"
// Define a unique identifier for your custom annotation
const
const DeprecatedId: typeof DeprecatedId
DeprecatedId
=
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
(
"some/unique/identifier/for/your/custom/annotation"
)
// Apply the custom annotation to the schema
const
const MyString: Schema.SchemaClass<string, string, never>
MyString
=
import Schema
Schema
.
class String
export String

@since3.10.0

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

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

annotations
({ [
const DeprecatedId: typeof DeprecatedId
DeprecatedId
]: true })
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const MyString: Schema.SchemaClass<string, string, never>
MyString
)
/*
Output:
[class SchemaClass] {
ast: StringKeyword {
annotations: {
[Symbol(@effect/docs/schema/annotation/Title)]: 'string',
[Symbol(@effect/docs/schema/annotation/Description)]: 'a string',
[Symbol(some/unique/identifier/for/your/custom/annotation)]: true
},
_tag: 'StringKeyword'
},
...
}
*/

To make your new custom annotation type-safe, you can use a module augmentation. In the next example, we want our custom annotation to be a boolean.

Example (Adding Type Safety to Custom Annotations)

import {
import Schema
Schema
} from "effect"
const
const DeprecatedId: typeof DeprecatedId
DeprecatedId
=
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
(
"some/unique/identifier/for/your/custom/annotation"
)
// Module augmentation
declare module "effect/Schema" {
namespace
namespace Annotations

@since3.10.0

Annotations
{
interface
interface Annotations.GenericSchema<A>

@since3.11.6

GenericSchema
<
function (type parameter) A in GenericSchema<A>
A
> extends
interface Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>

@since3.10.0

Schema
<
function (type parameter) A in GenericSchema<A>
A
> {
[
const DeprecatedId: typeof DeprecatedId
DeprecatedId
]?: boolean
}
}
}
const
const MyString: Schema.SchemaClass<string, string, never>
MyString
=
import Schema
Schema
.
class String
export String

@since3.10.0

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

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

annotations
({
[
const DeprecatedId: typeof DeprecatedId
DeprecatedId
]: "bad value"
Error ts(2418) ― Type of computed property's value is 'string', which is not assignable to type 'boolean'.
})

You can retrieve custom annotations using the SchemaAST.getAnnotation helper function.

Example (Retrieving a Custom Annotation)

import {
import SchemaAST
SchemaAST
,
import Schema
Schema
} from "effect"
import {
import Option

@since2.0.0

@since2.0.0

Option
} from "effect"
13 collapsed lines
const
const DeprecatedId: typeof DeprecatedId
DeprecatedId
=
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
(
"some/unique/identifier/for/your/custom/annotation"
)
declare module "effect/Schema" {
namespace
namespace Annotations

@since3.10.0

Annotations
{
interface
interface Annotations.GenericSchema<A>

@since3.11.6

GenericSchema
<
function (type parameter) A in GenericSchema<A>
A
> extends
interface Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>

@since3.10.0

Schema
<
function (type parameter) A in GenericSchema<A>
A
> {
[
const DeprecatedId: typeof DeprecatedId
DeprecatedId
]?: boolean
}
}
}
const
const MyString: Schema.SchemaClass<string, string, never>
MyString
=
import Schema
Schema
.
class String
export String

@since3.10.0

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

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

annotations
({ [
const DeprecatedId: typeof DeprecatedId
DeprecatedId
]: true })
// Helper function to check if a schema is marked as deprecated
const
const isDeprecated: <A, I, R>(schema: Schema.Schema<A, I, R>) => boolean
isDeprecated
= <
function (type parameter) A in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
A
,
function (type parameter) I in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
I
,
function (type parameter) R in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
R
>(
schema: Schema.Schema<A, I, R>
schema
:
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>(schema: Schema.Schema<A, I, R>): boolean
A
,
function (type parameter) I in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
I
,
function (type parameter) R in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
R
>): boolean =>
import SchemaAST
SchemaAST
.
const getAnnotation: <boolean>(key: symbol) => (annotated: SchemaAST.Annotated) => Option.Option<boolean> (+1 overload)

@since3.10.0

getAnnotation
<boolean>(
const DeprecatedId: typeof DeprecatedId
DeprecatedId
)(
schema: Schema.Schema<A, I, R>
schema
.
Schema<A, I, R>.ast: SchemaAST.AST
ast
).
Pipeable.pipe<Option.Option<boolean>, boolean>(this: Option.Option<boolean>, ab: (_: Option.Option<boolean>) => boolean): boolean (+21 overloads)
pipe
(
import Option

@since2.0.0

@since2.0.0

Option
.
const getOrElse: <boolean>(onNone: LazyArg<boolean>) => <A>(self: Option.Option<A>) => boolean | 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
(() => false)
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const isDeprecated: <string, string, never>(schema: Schema.Schema<string, string, never>) => boolean
isDeprecated
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
))
// Output: false
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
const isDeprecated: <string, string, never>(schema: Schema.Schema<string, string, never>) => boolean
isDeprecated
(
const MyString: Schema.SchemaClass<string, string, never>
MyString
))
// Output: true