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)
1import { import Schema
Schema } from "effect"2
3// Define a Password schema, starting with a string type4const const Password: Schema.refine<string, Schema.Schema<string, string, never>>
Password = import Schema
Schema.(alias) class String
export String
String5 // Add a custom error message for non-string values6 .(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 message9 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 fewer11 // with a custom error message for exceeding length12 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 schema18 (property) Annotations.Schema<string, readonly []>.identifier?: string
identifier: "Password",19 // Provide a title for the schema20 (property) Annotations.Doc<string>.title?: string
title: "password",21 // Include a description explaining what this schema represents22 (property) Annotations.Doc<string>.description?: string
description:23 "A password is a secret string used to authenticate a user",24 // Add examples for better clarity25 (property) Annotations.Doc<string>.examples?: readonly [string, ...string[]]
examples: ["1Ki77y", "jelly22fi$h"],26 // Include any additional documentation27 (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:
Annotation | Description |
---|---|
identifier | Assigns 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" . |
title | Sets 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. |
description | Provides a detailed explanation about the schema’s purpose, akin to a JSON Schema description. Used by TreeFormatter to provide more detailed error messages. |
documentation | Extends detailed documentation for the schema, beneficial for developers or automated documentation generation. |
examples | Lists examples of valid schema values, akin to the examples attribute in JSON Schema, useful for documentation and validation testing. |
default | Defines a default value for the schema, similar to the default attribute in JSON Schema, to ensure schemas are pre-populated where applicable. |
message | Customizes the error message for validation failures, improving clarity in outputs from tools like TreeFormatter and ArrayFormatter during decoding or validation errors. |
jsonSchema | Specifies annotations that affect the generation of JSON Schema documents, customizing how schemas are represented. |
arbitrary | Configures settings for generating Arbitrary test data. |
pretty | Configures settings for generating Pretty output. |
equivalence | Configures settings for evaluating data Equivalence. |
concurrency | Controls concurrency behavior, ensuring schemas perform optimally under concurrent operations. Refer to Concurrency Annotation for detailed usage. |
batching | Manages settings for batching operations to enhance performance when operations can be grouped. |
parseIssueTitle | Provides a custom title for parsing issues, enhancing error descriptions in outputs from TreeFormatter. See ParseIssueTitle Annotation for more information. |
parseOptions | Allows 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. |
decodingFallback | Provides 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:
Value | Description |
---|---|
number | Limits the maximum number of concurrent tasks. |
"unbounded" | All tasks run concurrently with no limit. |
"inherit" | Inherits concurrency settings from the parent context. |
undefined | Tasks 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.
1import { import Schema
Schema } from "effect"2import type { import Duration
Duration } from "effect"3import { import Effect
Effect } from "effect"4
5// Simulates an async task6const 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 true13 })14 )15 )16
17const 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
23import 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/*25Output:26Task 1 done27Task 2 done28Task 3 done29*/
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.
1import { import Schema
Schema } from "effect"2import type { import Duration
Duration } from "effect"3import { import Effect
Effect } from "effect"4
5// Simulates an async task6const 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 true13 })14 )15 )16
17const 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
23import 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/*25Output:26Task 2 done27Task 3 done28Task 1 done29*/
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.
1import { import Schema
Schema } from "effect"2import { import Either
Either } from "effect"3
4// Schema with a fallback value5const 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
9namespace 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 input11
12namespace 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.
1import { import Schema
Schema } from "effect"2import { import Effect
Effect } from "effect"3
4// Schema with logging and fallback5const 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 issue9 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 delay11 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 value13 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 logic18import 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.
log20)21/*22Output:23timestamp=2024-07-25T13:22:37.706Z level=INFO fiber=#0 message=Type24<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)
1import { import Schema
Schema } from "effect"2
3// Define a unique identifier for your custom annotation4const 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 schema9const 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
11namespace 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/*13Output: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)]: true20 },21 _tag: 'StringKeyword'22 },23 ...24}25*/
You can retrieve custom annotations using the AST.getAnnotation
helper method.
Example (Reading a Custom Annotation)
1import { import SchemaAST
SchemaAST, import Schema
Schema } from "effect"2import { import Option
Option } from "effect"3
7 collapsed lines
4// Define the unique identifier for the custom annotation5const 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 annotation10const 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 deprecated13const 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
18namespace 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: false19namespace 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