Skip to content

Schema Annotations

One of the key features of the Schema design is its flexibility and ability to be customized. This is achieved through “annotations.” Each node in the ast field of a schema has an annotations: Record<string | symbol, unknown> field, which allows you to attach additional information to the schema. You can manage these annotations using the annotations method or the Schema.annotations API.

Example (Using Annotations to Customize Schema)

1
import {
import Schema
Schema
} from "effect"
2
3
// Define a Password schema, starting with a string type
4
const
const Password: Schema.refine<string, Schema.Schema<string, string, never>>
Password
=
import Schema
Schema
.
(alias) class String export String
String
5
// Add a custom error message for non-string values
6
.
(method) Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.Schema<string, readonly []>): Schema.SchemaClass<string, string, never>

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

annotations
({
(property) Annotations.Schema<string, readonly []>.message?: MessageAnnotation
message
: () => "not a string" })
7
.
(method) Pipeable.pipe<Schema.SchemaClass<string, string, never>, Schema.filter<Schema.Schema<string, string, never>>, Schema.filter<Schema.Schema<string, string, never>>>(this: Schema.SchemaClass<...>, ab: (_: Schema.SchemaClass<...>) => Schema.filter<...>, bc: (_: Schema.filter<...>) => Schema.filter<...>): Schema.filter<...> (+21 overloads)
pipe
(
8
// Enforce non-empty strings and provide a custom error message
9
import Schema
Schema
.
const nonEmptyString: <string>(annotations?: Schema.Annotations.Filter<string, string> | undefined) => <I, R>(self: Schema.Schema<string, I, R>) => Schema.filter<Schema.Schema<string, I, R>>
nonEmptyString
({
(property) Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: () => "required" }),
10
// Restrict the string length to 10 characters or fewer
11
// with a custom error message for exceeding length
12
import Schema
Schema
.
const maxLength: <string>(maxLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <I, R>(self: Schema.Schema<string, I, R>) => Schema.filter<...>
maxLength
(10, {
13
(property) Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.message?: MessageAnnotation
message
: (
(parameter) issue: ParseIssue
issue
) => `${
(parameter) issue: ParseIssue
issue
.
(property) actual: unknown
actual
} is too long`
14
})
15
)
16
.
(method) Annotable<refine<string, Schema<string, string, never>>, string, string, never>.annotations(annotations: Schema.Annotations.Schema<string, readonly []>): Schema.refine<string, Schema.Schema<string, string, never>>

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

annotations
({
17
// Add a unique identifier for the schema
18
(property) Annotations.Schema<string, readonly []>.identifier?: string
identifier
: "Password",
19
// Provide a title for the schema
20
(property) Annotations.Doc<string>.title?: string
title
: "password",
21
// Include a description explaining what this schema represents
22
(property) Annotations.Doc<string>.description?: string
description
:
23
"A password is a secret string used to authenticate a user",
24
// Add examples for better clarity
25
(property) Annotations.Doc<string>.examples?: readonly [string, ...string[]]
examples
: ["1Ki77y", "jelly22fi$h"],
26
// Include any additional documentation
27
(property) Annotations.Doc<string>.documentation?: string
documentation
: `...technical information on Password schema...`
28
})

The following table provides an overview of common built-in annotations and their uses:

AnnotationDescription
identifierAssigns a unique identifier to the schema, ideal for TypeScript identifiers and code generation purposes. Commonly used in tools like TreeFormatter to clarify output. Examples include "Person", "Product".
titleSets a short, descriptive title for the schema, similar to a JSON Schema title. Useful for documentation or UI headings. It is also used by TreeFormatter to enhance readability of error messages.
descriptionProvides a detailed explanation about the schema’s purpose, akin to a JSON Schema description. Used by TreeFormatter to provide more detailed error messages.
documentationExtends detailed documentation for the schema, beneficial for developers or automated documentation generation.
examplesLists examples of valid schema values, akin to the examples attribute in JSON Schema, useful for documentation and validation testing.
defaultDefines a default value for the schema, similar to the default attribute in JSON Schema, to ensure schemas are pre-populated where applicable.
messageCustomizes the error message for validation failures, improving clarity in outputs from tools like TreeFormatter and ArrayFormatter during decoding or validation errors.
jsonSchemaSpecifies annotations that affect the generation of JSON Schema documents, customizing how schemas are represented.
arbitraryConfigures settings for generating Arbitrary test data.
prettyConfigures settings for generating Pretty output.
equivalenceConfigures settings for evaluating data Equivalence.
concurrencyControls concurrency behavior, ensuring schemas perform optimally under concurrent operations. Refer to Concurrency Annotation for detailed usage.
batchingManages settings for batching operations to enhance performance when operations can be grouped.
parseIssueTitleProvides a custom title for parsing issues, enhancing error descriptions in outputs from TreeFormatter. See ParseIssueTitle Annotation for more information.
parseOptionsAllows overriding of parsing options at the schema level, offering granular control over parsing behaviors. See Customizing Parsing Behavior at the Schema Level for application details.
decodingFallbackProvides a way to define custom fallback behaviors that trigger when decoding operations fail. Refer to Handling Decoding Errors with Fallbacks for detailed usage.

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.

1
import {
import Schema
Schema
} from "effect"
2
import type {
import Duration
Duration
} from "effect"
3
import {
import Effect
Effect
} from "effect"
4
5
// Simulates an async task
6
const
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
= (
(parameter) id: number
id
: number,
(parameter) duration: Duration.DurationInput
duration
:
import Duration
Duration
.
type DurationInput = number | bigint | Duration.Duration | [seconds: number, nanos: number] | `${number} nano` | `${number} nanos` | `${number} micro` | `${number} micros` | `${number} milli` | `${number} millis` | `${number} second` | `${number} seconds` | `${number} minute` | `${number} minutes` | ... 5 more ... | `${number} weeks`
DurationInput
) =>
7
import Schema
Schema
.
(alias) class String export String
String
.
(method) 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<...> (+21 overloads)
pipe
(
8
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<...> (+1 overload)
filterEffect
(() =>
9
import Effect
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<...> (+1 overload)
gen
(function* () {
10
yield*
import Effect
Effect
.
const sleep: (duration: Duration.DurationInput) => Effect.Effect<void>

Returns an effect that suspends for the specified duration. This method is asynchronous, and does not actually block the fiber executing the effect.

sleep
(
(parameter) duration: Duration.DurationInput
duration
)
11
namespace console 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js 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: ```js 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 ```

console
.
(method) 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)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js 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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(`Task ${
(parameter) id: number
id
} done`)
12
return true
13
})
14
)
15
)
16
17
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<...>, elements_1: Schema.filterEffect<...>, elements_2: Schema.filterEffect<...>): Schema.Tuple<...> (+1 overload)
Tuple
(
18
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(1, "30 millis"),
19
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(2, "10 millis"),
20
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(3, "20 millis")
21
)
22
23
import Effect
Effect
.
const runPromise: <readonly [string, string, string], ParseError>(effect: Effect.Effect<readonly [string, string, string], ParseError, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

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 [...], overrideOptions?: ParseOptions) => Effect.Effect<...>
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"]))
24
/*
25
Output:
26
Task 1 done
27
Task 2 done
28
Task 3 done
29
*/

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.

1
import {
import Schema
Schema
} from "effect"
2
import type {
import Duration
Duration
} from "effect"
3
import {
import Effect
Effect
} from "effect"
4
5
// Simulates an async task
6
const
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
= (
(parameter) id: number
id
: number,
(parameter) duration: Duration.DurationInput
duration
:
import Duration
Duration
.
type DurationInput = number | bigint | Duration.Duration | [seconds: number, nanos: number] | `${number} nano` | `${number} nanos` | `${number} micro` | `${number} micros` | `${number} milli` | `${number} millis` | `${number} second` | `${number} seconds` | `${number} minute` | `${number} minutes` | ... 5 more ... | `${number} weeks`
DurationInput
) =>
7
import Schema
Schema
.
(alias) class String export String
String
.
(method) 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<...> (+21 overloads)
pipe
(
8
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<...> (+1 overload)
filterEffect
(() =>
9
import Effect
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<...> (+1 overload)
gen
(function* () {
10
yield*
import Effect
Effect
.
const sleep: (duration: Duration.DurationInput) => Effect.Effect<void>

Returns an effect that suspends for the specified duration. This method is asynchronous, and does not actually block the fiber executing the effect.

sleep
(
(parameter) duration: Duration.DurationInput
duration
)
11
namespace console 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js 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: ```js 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 ```

console
.
(method) 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)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js 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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(`Task ${
(parameter) id: number
id
} done`)
12
return true
13
})
14
)
15
)
16
17
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<...>, elements_1: Schema.filterEffect<...>, elements_2: Schema.filterEffect<...>): Schema.Tuple<...> (+1 overload)
Tuple
(
18
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(1, "30 millis"),
19
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(2, "10 millis"),
20
const item: (id: number, duration: Duration.DurationInput) => Schema.filterEffect<typeof Schema.String, never>
item
(3, "20 millis")
21
).
(method) 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<...>]>

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

annotations
({
(property) Annotations.Schema<readonly [string, string, string], readonly []>.concurrency?: ConcurrencyAnnotation
concurrency
: "unbounded" })
22
23
import Effect
Effect
.
const runPromise: <readonly [string, string, string], ParseError>(effect: Effect.Effect<readonly [string, string, string], ParseError, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

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 [...], overrideOptions?: ParseOptions) => Effect.Effect<...>
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"]))
24
/*
25
Output:
26
Task 2 done
27
Task 3 done
28
Task 1 done
29
*/

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.

1
import {
import Schema
Schema
} from "effect"
2
import {
import Either
Either
} from "effect"
3
4
// Schema with a fallback value
5
const
const schema: Schema.SchemaClass<string, string, never>
schema
=
import Schema
Schema
.
(alias) class String export String
String
.
(method) Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.Schema<string, readonly []>): Schema.SchemaClass<string, string, never>

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

annotations
({
6
(property) Annotations.Schema<string, readonly []>.decodingFallback?: DecodingFallbackAnnotation<string>
decodingFallback
: () =>
import Either
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.

right
("<fallback>")
7
})
8
9
namespace console 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js 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: ```js 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 ```

console
.
(method) 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)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js 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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(
import Schema
Schema
.
(alias) decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string export decodeUnknownSync
decodeUnknownSync
(
const schema: Schema.SchemaClass<string, string, never>
schema
)("valid input"))
10
// Output: valid input
11
12
namespace console 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js 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: ```js 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 ```

console
.
(method) 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)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js 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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(
import Schema
Schema
.
(alias) decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string export decodeUnknownSync
decodeUnknownSync
(
const schema: Schema.SchemaClass<string, string, never>
schema
)(null))
13
// 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.

1
import {
import Schema
Schema
} from "effect"
2
import {
import Effect
Effect
} from "effect"
3
4
// Schema with logging and fallback
5
const
const schemaWithLog: Schema.SchemaClass<string, string, never>
schemaWithLog
=
import Schema
Schema
.
(alias) class String export String
String
.
(method) Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.Schema<string, readonly []>): Schema.SchemaClass<string, string, never>

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

annotations
({
6
(property) Annotations.Schema<string, readonly []>.decodingFallback?: DecodingFallbackAnnotation<string>
decodingFallback
: (
(parameter) issue: ParseIssue
issue
) =>
7
import Effect
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<...> (+1 overload)
gen
(function* () {
8
// Log the error issue
9
yield*
import Effect
Effect
.
const log: (...message: ReadonlyArray<any>) => Effect.Effect<void, never, never>

Logs one or more messages or error causes at the current log level, which is INFO by default. This function allows logging multiple items at once and can include detailed error information using `Cause` instances. To adjust the log level, use the `Logger.withMinimumLogLevel` function.

log
(
(parameter) issue: ParseIssue
issue
.
(property) _tag: "Type" | "Missing" | "Unexpected" | "Forbidden" | "Pointer" | "Refinement" | "Transformation" | "Composite"
_tag
)
10
// Simulate a delay
11
yield*
import Effect
Effect
.
const sleep: (duration: DurationInput) => Effect.Effect<void>

Returns an effect that suspends for the specified duration. This method is asynchronous, and does not actually block the fiber executing the effect.

sleep
(10)
12
// Return a fallback value
13
return yield*
import Effect
Effect
.
const succeed: <string>(value: string) => Effect.Effect<string, never, never>

Creates an `Effect` that succeeds with the provided value. Use this function to represent a successful computation that yields a value of type `A`. The effect does not fail and does not require any environmental context.

succeed
("<fallback>")
14
})
15
})
16
17
// Run the effectful fallback logic
18
import Effect
Effect
.
const runPromise: <string, ParseError>(effect: Effect.Effect<string, ParseError, never>, options?: { readonly signal?: AbortSignal; } | undefined) => Promise<...>

Executes an effect and returns a `Promise` that resolves with the result. Use `runPromise` when working with asynchronous effects and you need to integrate with code that uses Promises. If the effect fails, the returned Promise will be rejected with the error.

runPromise
(
import Schema
Schema
.
const decodeUnknown: <string, string, never>(schema: Schema.Schema<string, string, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Effect.Effect<...>
decodeUnknown
(
const schemaWithLog: Schema.SchemaClass<string, string, never>
schemaWithLog
)(null)).
(method) Promise<string>.then<void, never>(onfulfilled?: ((value: string) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

then
(
19
namespace console 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js 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: ```js 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 ```

console
.
(method) 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)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js 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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

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

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)

1
import {
import Schema
Schema
} from "effect"
2
3
// Define a unique identifier for your custom annotation
4
const
const DeprecatedId: typeof DeprecatedId
DeprecatedId
=
var Symbol: SymbolConstructor
Symbol
.
(method) 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.

for
(
5
"some/unique/identifier/for/your/custom/annotation"
6
)
7
8
// Apply the custom annotation to the schema
9
const
const MyString: Schema.SchemaClass<string, string, never>
MyString
=
import Schema
Schema
.
(alias) class String export String
String
.
(method) Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.Schema<string, readonly []>): 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 })
10
11
namespace console 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js 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: ```js 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 ```

console
.
(method) 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)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js 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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(
const MyString: Schema.SchemaClass<string, string, never>
MyString
)
12
/*
13
Output:
14
[class SchemaClass] {
15
ast: StringKeyword {
16
annotations: {
17
[Symbol(@effect/docs/schema/annotation/Title)]: 'string',
18
[Symbol(@effect/docs/schema/annotation/Description)]: 'a string',
19
[Symbol(some/unique/identifier/for/your/custom/annotation)]: true
20
},
21
_tag: 'StringKeyword'
22
},
23
...
24
}
25
*/

You can retrieve custom annotations using the AST.getAnnotation helper method.

Example (Reading a Custom Annotation)

1
import {
import SchemaAST
SchemaAST
,
import Schema
Schema
} from "effect"
2
import {
import Option
Option
} from "effect"
3
7 collapsed lines
4
// Define the unique identifier for the custom annotation
5
const
const DeprecatedId: typeof DeprecatedId
DeprecatedId
=
var Symbol: SymbolConstructor
Symbol
.
(method) 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.

for
(
6
"some/unique/identifier/for/your/custom/annotation"
7
)
8
9
// Create a schema with the custom annotation
10
const
const MyString: Schema.SchemaClass<string, string, never>
MyString
=
import Schema
Schema
.
(alias) class String export String
String
.
(method) Annotable<SchemaClass<string, string, never>, string, string, never>.annotations(annotations: Schema.Annotations.Schema<string, readonly []>): 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 })
11
12
// Helper function to check if a schema is marked as deprecated
13
const
const isDeprecated: <A, I, R>(schema: Schema.Schema<A, I, R>) => boolean
isDeprecated
= <
(type parameter) A in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
A
,
(type parameter) I in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
I
,
(type parameter) R in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
R
>(
(parameter) schema: Schema.Schema<A, I, R>
schema
:
import Schema
Schema
.
interface Schema<in out A, in out I = A, out R = never> namespace Schema
Schema
<
(type parameter) A in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
A
,
(type parameter) I in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
I
,
(type parameter) R in <A, I, R>(schema: Schema.Schema<A, I, R>): boolean
R
>): boolean =>
14
import SchemaAST
SchemaAST
.
const getAnnotation: <boolean>(key: symbol) => (annotated: SchemaAST.Annotated) => Option.Option<boolean> (+1 overload)
getAnnotation
<boolean>(
const DeprecatedId: typeof DeprecatedId
DeprecatedId
)(
(parameter) schema: Schema.Schema<A, I, R>
schema
.
(property) Schema<A, I, R>.ast: SchemaAST.AST
ast
).
(method) Pipeable.pipe<Option.Option<boolean>, boolean>(this: Option.Option<boolean>, ab: (_: Option.Option<boolean>) => boolean): boolean (+21 overloads)
pipe
(
15
import Option
Option
.
const getOrElse: <boolean>(onNone: LazyArg<boolean>) => <A>(self: Option.Option<A>) => boolean | A (+1 overload)

Returns the value of the `Option` if it is `Some`, otherwise returns `onNone`

getOrElse
(() => false)
16
)
17
18
namespace console 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js 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: ```js 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 ```

console
.
(method) 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)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js 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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

log
(
const isDeprecated: <string, string, never>(schema: Schema.Schema<string, string, never>) => boolean
isDeprecated
(
import Schema
Schema
.
(alias) class String export String
String
)) // Output: false
19
namespace console 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). 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`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js 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: ```js 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 ```

console
.
(method) 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)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)). ```js 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()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.

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