Getting Started
You can import the necessary types and functions from the effect/Schema
module:
Example (Namespace Import)
import * as Schema from "effect/Schema"
Example (Named Import)
import { Schema } from "effect"
One common way to define a Schema
is by utilizing the Struct
constructor.
This constructor allows you to create a new schema that outlines an object with specific properties.
Each property in the object is defined by its own schema, which specifies the data type and any validation rules.
Example
Consider the following schema that describes a person object with:
- a
name
property of typestring
- an
age
property of typenumber
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})
Once you’ve defined a schema (Schema<Type, Encoded, Context>
), you can extract the inferred type Type
in two ways:
- Using the
Schema.Type
utility. - Using the
Type
field defined on your schema.
Example
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})7
8// 1. Using the Schema.Type utility9type type Person = {
readonly name: string;
readonly age: number;
}
Person = import Schema
Schema.namespace Schema
Schema.type Schema<in out A, in out I = A, out R = never>.Type<S> = S extends Schema.Schema.Variance<infer A, infer _I, infer _R> ? A : never
Type<typeof const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person>10
11// 2. Using the `Type` field12type type Person2 = {
readonly name: string;
readonly age: number;
}
Person2 = typeof const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person.(property) Schema<{ readonly name: string; readonly age: number; }, { readonly name: string; readonly age: number; }, never>.Type: {
readonly name: string;
readonly age: number;
}
Type
The result is equivalent to:
type Person = { name: string age: number}
Alternatively, you can extract the Person
type using the interface
keyword.
Example
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})7
8interface interface Person
Person extends import Schema
Schema.namespace Schema
Schema.type Schema<in out A, in out I = A, out R = never>.Type<S> = S extends Schema.Schema.Variance<infer A, infer _I, infer _R> ? A : never
Type<typeof const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person> {}
Both approaches yield the same result, but using an interface provides benefits such as performance advantages and improved readability.
In cases where in a Schema<Type, Encoded, Context>
the Encoded
type differs from the Type
type, you can extract the inferred Encoded
in two ways:
- Using the
Schema.Encoded
utility. - Using the
Encoded
field defined on your schema.
Example
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 // a schema that decodes a string to a number6 (property) age: typeof Schema.NumberFromString
age: import Schema
Schema.class NumberFromString
This schema transforms a `string` into a `number` by parsing the string using the `parse` function of the `effect/Number` module.
It returns an error if the value can't be converted (for example when non-numeric characters are provided).
The following special string values are supported: "NaN", "Infinity", "-Infinity".
NumberFromString7})8
9// 1. Using the Schema.Encoded utility10type type PersonEncoded = {
readonly name: string;
readonly age: string;
}
PersonEncoded = import Schema
Schema.namespace Schema
Schema.type Schema<in out A, in out I = A, out R = never>.Encoded<S> = S extends Schema.Schema.Variance<infer _A, infer I, infer _R> ? I : never
Encoded<typeof const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>
Person>11
12// 2. Using the `Encoded` field13type type PersonEncoded2 = {
readonly name: string;
readonly age: string;
}
PersonEncoded2 = typeof const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>
Person.(property) Schema<{ readonly name: string; readonly age: number; }, { readonly name: string; readonly age: string; }, never>.Encoded: {
readonly name: string;
readonly age: string;
}
Encoded
The result is equivalent to:
type PersonEncoded = { name: string age: string}
Note that age
is of type string
in the Encoded
type of the schema and is of type number
in the Type
type of the schema.
Alternatively, you can extract the PersonEncoded
type using the interface
keyword.
Example
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 // a schema that decodes a string to a number6 (property) age: typeof Schema.NumberFromString
age: import Schema
Schema.class NumberFromString
This schema transforms a `string` into a `number` by parsing the string using the `parse` function of the `effect/Number` module.
It returns an error if the value can't be converted (for example when non-numeric characters are provided).
The following special string values are supported: "NaN", "Infinity", "-Infinity".
NumberFromString7})8
9interface interface PersonEncoded
PersonEncoded extends import Schema
Schema.namespace Schema
Schema.type Schema<in out A, in out I = A, out R = never>.Encoded<S> = S extends Schema.Schema.Variance<infer _A, infer I, infer _R> ? I : never
Encoded<typeof const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>
Person> {}
Both approaches yield the same result, but using an interface provides benefits such as performance advantages and improved readability.
You can also extract the inferred type Context
that represents the context required by the schema.
Example
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})7
8// 1. Using the Schema.Context utility9type type PersonContext = never
PersonContext = import Schema
Schema.namespace Schema
Schema.type Schema<in out A, in out I = A, out R = never>.Context<S> = S extends Schema.Schema.Variance<infer _A, infer _I, infer R> ? R : never
Context<typeof const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person>10
11// 2. Using the `Context` field12type type PersonContext2 = never
PersonContext2 = typeof const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person.(property) Schema<{ readonly name: string; readonly age: number; }, { readonly name: string; readonly age: number; }, never>.Context: never
Context
When defining a schema, you may want to create a schema with an opaque type. This is useful when you want to hide the internal structure of the schema and only expose the type of the schema.
Example
To create a schema with an opaque type, you can use the following technique that re-declares the schema:
1import { import Schema
Schema } from "effect"2
3const const _Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
_Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})7
8interface interface Person
Person extends import Schema
Schema.namespace Schema
Schema.type Schema<in out A, in out I = A, out R = never>.Type<S> = S extends Schema.Schema.Variance<infer A, infer _I, infer _R> ? A : never
Type<typeof const _Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
_Person> {}9
10// Re-declare the schema to create a schema with an opaque type11const const Person: Schema.Schema<Person, Person, never>
Person: import Schema
Schema.interface Schema<in out A, in out I = A, out R = never>
namespace Schema
Schema<interface Person
Person> = const _Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
_Person
Alternatively, you can use the Class APIs (see the Class APIs section for more details).
Note that the technique shown above becomes more complex when the schema is defined such that Type
is different from Encoded
.
Example
1import { import Schema
Schema } from "effect"2
3const const _Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>
_Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 // a schema that decodes a string to a number6 (property) age: typeof Schema.NumberFromString
age: import Schema
Schema.class NumberFromString
This schema transforms a `string` into a `number` by parsing the string using the `parse` function of the `effect/Number` module.
It returns an error if the value can't be converted (for example when non-numeric characters are provided).
The following special string values are supported: "NaN", "Infinity", "-Infinity".
NumberFromString7})8
9interface interface Person
Person extends import Schema
Schema.namespace Schema
Schema.type Schema<in out A, in out I = A, out R = never>.Type<S> = S extends Schema.Schema.Variance<infer A, infer _I, infer _R> ? A : never
Type<typeof const _Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>
_Person> {}10
11interface interface PersonEncoded
PersonEncoded extends import Schema
Schema.namespace Schema
Schema.type Schema<in out A, in out I = A, out R = never>.Encoded<S> = S extends Schema.Schema.Variance<infer _A, infer I, infer _R> ? I : never
Encoded<typeof const _Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>
_Person> {}12
13// Re-declare the schema to create a schema with an opaque type14const const Person: Schema.Schema<Person, PersonEncoded, never>
Person: import Schema
Schema.interface Schema<in out A, in out I = A, out R = never>
namespace Schema
Schema<interface Person
Person, interface PersonEncoded
PersonEncoded> = const _Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.NumberFromString;
}>
_Person
In this case, the field "age"
is of type string
in the Encoded
type of the schema and is of type number
in the Type
type of the schema. Therefore, we need to define two interfaces (PersonEncoded
and Person
) and use both to redeclare our final schema Person
.
It’s important to note that by default, most constructors exported by
effect/Schema
return readonly
types.
Example
For instance, in the Person
schema below:
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})
the resulting inferred Type
would be:
{ readonly name: string; readonly age: number;}
When working with unknown data types in TypeScript, decoding them into a known structure can be challenging. Luckily, effect/Schema
provides several functions to help with this process. Let’s explore how to decode unknown values using these functions.
API | Description |
---|---|
decodeUnknownSync | Synchronously decodes a value and throws an error if parsing fails. |
decodeUnknownOption | Decodes a value and returns an Option type. |
decodeUnknownEither | Decodes a value and returns an Either type. |
decodeUnknownPromise | Decodes a value and returns a Promise . |
decodeUnknown | Decodes a value and returns an Effect. |
The Schema.decodeUnknownSync
function is useful when you want to parse a value and immediately throw an error if the parsing fails.
Example
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})7
8// Simulate an unknown input9const const input: unknown
input: unknown = { (property) name: string
name: "Alice", (property) age: number
age: 30 }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(import Schema
Schema.(alias) decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync
decodeUnknownSync(const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person)(const input: unknown
input))12// Output: { name: 'Alice', age: 30 }13
14namespace 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<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync
decodeUnknownSync(const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person)(null))15/*16throws:17ParseError: Expected { readonly name: string; readonly age: number }, actual null18*/
The Schema.decodeUnknownEither
function returns an Either type representing success or failure.
Example
1import { import Schema
Schema } from "effect"2import { import Either
Either } from "effect"3
4const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({5 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,6 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number7})8
9const const decode: (u: unknown, overrideOptions?: ParseOptions) => Either.Either<{
readonly name: string;
readonly age: number;
}, ParseError>
decode = import Schema
Schema.const decodeUnknownEither: <{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Either.Either<...>
decodeUnknownEither(const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person)10
11// Simulate an unknown input12const const input: unknown
input: unknown = { (property) name: string
name: "Alice", (property) age: number
age: 30 }13
14const const result1: Either.Either<{
readonly name: string;
readonly age: number;
}, ParseError>
result1 = const decode: (u: unknown, overrideOptions?: ParseOptions) => Either.Either<{
readonly name: string;
readonly age: number;
}, ParseError>
decode(const input: unknown
input)15if (import Either
Either.const isRight: <{
readonly name: string;
readonly age: number;
}, ParseError>(self: Either.Either<{
readonly name: string;
readonly age: number;
}, ParseError>) => self is Either.Right<...>
Determine if a `Either` is a `Right`.
isRight(const result1: Either.Either<{
readonly name: string;
readonly age: number;
}, ParseError>
result1)) {16 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 result1: Either.Right<ParseError, {
readonly name: string;
readonly age: number;
}>
result1.(property) Right<ParseError, { readonly name: string; readonly age: number; }>.right: {
readonly name: string;
readonly age: number;
}
right)17 /*18 Output:19 { name: "Alice", age: 30 }20 */21}22
23const const result2: Either.Either<{
readonly name: string;
readonly age: number;
}, ParseError>
result2 = const decode: (u: unknown, overrideOptions?: ParseOptions) => Either.Either<{
readonly name: string;
readonly age: number;
}, ParseError>
decode(null)24if (import Either
Either.const isLeft: <{
readonly name: string;
readonly age: number;
}, ParseError>(self: Either.Either<{
readonly name: string;
readonly age: number;
}, ParseError>) => self is Either.Left<...>
Determine if a `Either` is a `Left`.
isLeft(const result2: Either.Either<{
readonly name: string;
readonly age: number;
}, ParseError>
result2)) {25 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 result2: Either.Left<ParseError, {
readonly name: string;
readonly age: number;
}>
result2.(property) Left<ParseError, { readonly name: string; readonly age: number; }>.left: ParseError
left)26 /*27 Output:28 {29 _id: 'ParseError',30 message: 'Expected { readonly name: string; readonly age: number }, actual null'31 }32 */33}
If your schema involves asynchronous transformations, the Schema.decodeUnknownSync
and Schema.decodeUnknownEither
functions will not be suitable.
In such cases, you should use the Schema.decodeUnknown
function, which returns an Effect.
Example
1import { import Schema
Schema } from "effect"2import { import Effect
Effect } from "effect"3
4const const PersonId: typeof Schema.Number
PersonId = import Schema
Schema.(alias) class Number
export Number
Number5
6const const Person: Schema.Struct<{
id: typeof Schema.Number;
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
id: typeof Schema.Number;
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
id: typeof Schema.Number;
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<...> (+1 overload)
namespace Struct
Struct({7 (property) id: typeof Schema.Number
id: const PersonId: typeof Schema.Number
PersonId,8 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,9 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number10})11
12const const asyncSchema: Schema.transformOrFail<typeof Schema.Number, Schema.Struct<{
id: typeof Schema.Number;
name: typeof Schema.String;
age: typeof Schema.Number;
}>, never>
asyncSchema = import Schema
Schema.const transformOrFail: <Schema.Struct<{
id: typeof Schema.Number;
name: typeof Schema.String;
age: typeof Schema.Number;
}>, typeof Schema.Number, never, never>(from: typeof Schema.Number, to: Schema.Struct<...>, options: {
...;
} | {
...;
}) => Schema.transformOrFail<...> (+1 overload)
Create a new `Schema` by transforming the input and output of an existing `Schema`
using the provided decoding functions.
transformOrFail(const PersonId: typeof Schema.Number
PersonId, const Person: Schema.Struct<{
id: typeof Schema.Number;
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person, {13 (property) strict?: true
strict: true,14 // Simulate an async transformation15 (property) decode: (fromA: number, options: ParseOptions, ast: Transformation, fromI: number) => Effect.Effect<{
readonly id: number;
readonly name: string;
readonly age: number;
}, ParseIssue, never>
decode: ((parameter) id: number
id) =>16 import Effect
Effect.const succeed: <{
id: number;
name: string;
age: number;
}>(value: {
id: number;
name: string;
age: number;
}) => Effect.Effect<{
id: number;
name: string;
age: number;
}, 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({ (property) id: number
id, (property) name: string
name: "name", (property) age: number
age: 18 }).(method) Pipeable.pipe<Effect.Effect<{
id: number;
name: string;
age: number;
}, never, never>, Effect.Effect<{
id: number;
name: string;
age: number;
}, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<{
id: number;
name: string;
age: number;
}, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(17 import Effect
Effect.const delay: (duration: DurationInput) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay("10 millis")18 ),19 (property) encode: (toI: {
readonly id: number;
readonly name: string;
readonly age: number;
}, options: ParseOptions, ast: Transformation, toA: {
...;
}) => Effect.Effect<...>
encode: ((parameter) person: {
readonly id: number;
readonly name: string;
readonly age: number;
}
person) =>20 import Effect
Effect.const succeed: <number>(value: number) => Effect.Effect<number, 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((parameter) person: {
readonly id: number;
readonly name: string;
readonly age: number;
}
person.(property) id: number
id).(method) Pipeable.pipe<Effect.Effect<number, never, never>, Effect.Effect<number, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<number, never, never>) => Effect.Effect<number, never, never>): Effect.Effect<...> (+21 overloads)
pipe(import Effect
Effect.const delay: (duration: DurationInput) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> (+1 overload)
Returns an effect that is delayed from this effect by the specified
`Duration`.
delay("10 millis"))21})22
23namespace 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.const decodeUnknownEither: <{
readonly id: number;
readonly name: string;
readonly age: number;
}, number>(schema: Schema.Schema<{
readonly id: number;
readonly name: string;
readonly age: number;
}, number, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Either<...>
decodeUnknownEither(const asyncSchema: Schema.transformOrFail<typeof Schema.Number, Schema.Struct<{
id: typeof Schema.Number;
name: typeof Schema.String;
age: typeof Schema.Number;
}>, never>
asyncSchema)(1))24/*25Output:26{27 _id: 'Either',28 _tag: 'Left',29 left: {30 _id: 'ParseError',31 message: '(number <-> { readonly id: number; readonly name: string; readonly age: number })\n' +32 '└─ cannot be be resolved synchronously, this is caused by using runSync on an effect that performs async work'33 }34}35*/36
37import Effect
Effect.const runPromise: <{
readonly id: number;
readonly name: string;
readonly age: number;
}, ParseError>(effect: Effect.Effect<{
readonly id: number;
readonly name: string;
readonly age: number;
}, 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: <{
readonly id: number;
readonly name: string;
readonly age: number;
}, number, never>(schema: Schema.Schema<{
readonly id: number;
readonly name: string;
readonly age: number;
}, number, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Effect.Effect<...>
decodeUnknown(const asyncSchema: Schema.transformOrFail<typeof Schema.Number, Schema.Struct<{
id: typeof Schema.Number;
name: typeof Schema.String;
age: typeof Schema.Number;
}>, never>
asyncSchema)(1)).(method) Promise<{ readonly id: number; readonly name: string; readonly age: number; }>.then<void, never>(onfulfilled?: ((value: {
readonly id: number;
readonly name: string;
readonly age: number;
}) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(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)38/*39Output:40{ id: 1, name: 'name', age: 18 }41*/
In the code above, the first approach using Schema.decodeUnknownEither
results in an error indicating that the transformation cannot be resolved synchronously.
This occurs because Schema.decodeUnknownEither
is not designed for async operations.
The second approach, which uses Schema.decodeUnknown
, works correctly, allowing you to handle asynchronous transformations and return the expected result.
The Schema
module provides several encode*
functions to encode data according to a schema:
API | Description |
---|---|
encodeSync | Synchronously encodes data and throws an error if encoding fails. |
encodeOption | Encodes data and returns an Option type. |
encodeEither | Encodes data and returns an Either type representing success or failure. |
encodePromise | Encodes data and returns a Promise . |
encode | Encodes data and returns an Effect. |
Example (Schema.encodeSync
)
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.NonEmptyString;
age: typeof Schema.NumberFromString;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.NonEmptyString;
age: typeof Schema.NumberFromString;
}>(fields: {
name: typeof Schema.NonEmptyString;
age: typeof Schema.NumberFromString;
}): Schema.Struct<{
name: typeof Schema.NonEmptyString;
age: typeof Schema.NumberFromString;
}> (+1 overload)
namespace Struct
Struct({4 // A schema that ensures a string is not empty5 (property) name: typeof Schema.NonEmptyString
name: import Schema
Schema.class NonEmptyString
NonEmptyString,6 // A schema that can decode a string to a number7 // and encode a number to a string8 (property) age: typeof Schema.NumberFromString
age: import Schema
Schema.class NumberFromString
This schema transforms a `string` into a `number` by parsing the string using the `parse` function of the `effect/Number` module.
It returns an error if the value can't be converted (for example when non-numeric characters are provided).
The following special string values are supported: "NaN", "Infinity", "-Infinity".
NumberFromString9})10
11// Valid input12namespace 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) encodeSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: string;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: string;
}, never>, options?: ParseOptions): (a: {
readonly name: string;
readonly age: number;
}, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: string;
}
export encodeSync
encodeSync(const Person: Schema.Struct<{
name: typeof Schema.NonEmptyString;
age: typeof Schema.NumberFromString;
}>
Person)({ (property) name: string
name: "Alice", (property) age: number
age: 30 }))13// Output: { name: 'Alice', age: '30' }14
15// Invalid input16namespace 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) encodeSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: string;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: string;
}, never>, options?: ParseOptions): (a: {
readonly name: string;
readonly age: number;
}, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: string;
}
export encodeSync
encodeSync(const Person: Schema.Struct<{
name: typeof Schema.NonEmptyString;
age: typeof Schema.NumberFromString;
}>
Person)({ (property) name: string
name: "", (property) age: number
age: 30 }))17/*18throws:19ParseError: { readonly name: NonEmptyString; readonly age: NumberFromString }20└─ ["name"]21 └─ NonEmptyString22 └─ Predicate refinement failure23 └─ Expected NonEmptyString, actual ""24*/
Note that during encoding, the number value 30
was converted to a string "30"
.
Although it is generally recommended to define schemas that support both decoding and encoding, there are situations where encoding support might be impossible.
In such cases, the Forbidden
error can be used to handle unsupported encoding.
Example (Using Forbidden
for Unsupported Encoding)
Here is an example of a transformation that never fails during decoding. It returns an Either containing either the decoded value or the original input. For encoding, it is reasonable to not support it and use Forbidden
as the result.
1import { import Either
Either, import ParseResult
ParseResult, import Schema
Schema } from "effect"2
3// Define a schema that safely decodes to Either type4export const const SafeDecode: <A, I>(self: Schema.Schema<A, I, never>) => Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
SafeDecode = <(type parameter) A in <A, I>(self: Schema.Schema<A, I, never>): Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
A, (type parameter) I in <A, I>(self: Schema.Schema<A, I, never>): Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
I>((parameter) self: Schema.Schema<A, I, never>
self: import Schema
Schema.interface Schema<in out A, in out I = A, out R = never>
namespace Schema
Schema<(type parameter) A in <A, I>(self: Schema.Schema<A, I, never>): Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
A, (type parameter) I in <A, I>(self: Schema.Schema<A, I, never>): Schema.transformOrFail<typeof Schema.Unknown, Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, never>
I, never>) => {5 const const decodeUnknownEither: (u: unknown, overrideOptions?: ParseOptions) => Either.Either<A, ParseResult.ParseError>
decodeUnknownEither = import Schema
Schema.const decodeUnknownEither: <A, I>(schema: Schema.Schema<A, I, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Either.Either<...>
decodeUnknownEither((parameter) self: Schema.Schema<A, I, never>
self)6 return import Schema
Schema.const transformOrFail: <Schema.EitherFromSelf<Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>, typeof Schema.Unknown, never, never>(from: typeof Schema.Unknown, to: Schema.EitherFromSelf<...>, options: {
...;
} | {
...;
}) => Schema.transformOrFail<...> (+1 overload)
Create a new `Schema` by transforming the input and output of an existing `Schema`
using the provided decoding functions.
transformOrFail(7 import Schema
Schema.class Unknown
Unknown,8 import Schema
Schema.const EitherFromSelf: <Schema.SchemaClass<A, A, never>, typeof Schema.Unknown>({ left, right }: {
readonly left: typeof Schema.Unknown;
readonly right: Schema.SchemaClass<A, A, never>;
}) => Schema.EitherFromSelf<...>
EitherFromSelf({9 (property) left: typeof Schema.Unknown
left: import Schema
Schema.class Unknown
Unknown,10 (property) right: Schema.SchemaClass<A, A, never>
right: import Schema
Schema.const typeSchema: <A, I, never>(schema: Schema.Schema<A, I, never>) => Schema.SchemaClass<A, A, never>
The `typeSchema` function allows you to extract the `Type` portion of a
schema, creating a new schema that conforms to the properties defined in the
original schema without considering the initial encoding or transformation
processes.
typeSchema((parameter) self: Schema.Schema<A, I, never>
self)11 }),12 {13 (property) strict?: true
strict: true,14 (property) decode: (fromA: unknown, options: ParseOptions, ast: Transformation, fromI: unknown) => Effect<Either.Either<A, unknown>, ParseResult.ParseIssue, never>
decode: ((parameter) input: unknown
input) =>15 import ParseResult
ParseResult.const succeed: <Either.Either<A, unknown>>(a: Either.Either<A, unknown>) => Either.Either<Either.Either<A, unknown>, ParseResult.ParseIssue>
succeed(16 import Either
Either.const mapLeft: <A, ParseResult.ParseError, unknown>(self: Either.Either<A, ParseResult.ParseError>, f: (left: ParseResult.ParseError) => unknown) => Either.Either<...> (+1 overload)
Maps the `Left` side of an `Either` value to a new `Either` value.
mapLeft(const decodeUnknownEither: (u: unknown, overrideOptions?: ParseOptions) => Either.Either<A, ParseResult.ParseError>
decodeUnknownEither((parameter) input: unknown
input), () => (parameter) input: unknown
input)17 ),18 (property) encode: (toI: Either.Either<A, unknown>, options: ParseOptions, ast: Transformation, toA: Either.Either<A, unknown>) => Effect<...>
encode: ((parameter) actual: Either.Either<A, unknown>
actual, (parameter) _: ParseOptions
_, (parameter) ast: Transformation
ast) =>19 import Either
Either.const match: <A, unknown, Either.Either<never, ParseResult.ParseIssue>, Either.Either<A, ParseResult.ParseIssue>>(self: Either.Either<A, unknown>, options: {
...;
}) => Either.Either<...> | Either.Either<...> (+1 overload)
Takes two functions and an `Either` value, if the value is a `Left` the inner value is applied to the `onLeft function,
if the value is a `Right` the inner value is applied to the `onRight` function.
match((parameter) actual: Either.Either<A, unknown>
actual, {20 // Encoding a Left value is not supported21 (property) onLeft: (left: unknown) => Either.Either<never, ParseResult.ParseIssue>
onLeft: () =>22 import ParseResult
ParseResult.const fail: (issue: ParseResult.ParseIssue) => Either.Either<never, ParseResult.ParseIssue>
fail(23 new import ParseResult
ParseResult.constructor Forbidden(ast: AST, actual: unknown, message?: string | undefined): ParseResult.Forbidden
The `Forbidden` variant of the `ParseIssue` type represents a forbidden operation, such as when encountering an Effect that is not allowed to execute (e.g., using `runSync`).
Forbidden(24 (parameter) ast: Transformation
ast,25 (parameter) actual: Either.Either<A, unknown>
actual,26 "cannot encode a Left"27 )28 ),29 // Successfully encode a Right value30 (property) onRight: (right: A) => Either.Either<A, ParseResult.ParseIssue>
onRight: import ParseResult
ParseResult.const succeed: <A>(a: A) => Either.Either<A, ParseResult.ParseIssue>
succeed31 })32 }33 )34}
Explanation
- Decoding: The
SafeDecode
function ensures that decoding never fails. It wraps the decoded value in an Either, where a successful decoding results in aRight
and a failed decoding results in aLeft
containing the original input. - Encoding: The encoding process uses the
Forbidden
error to indicate that encoding aLeft
value is not supported. OnlyRight
values are successfully encoded.
The Schema.decodeUnknownEither
and Schema.encodeEither
functions returns a Either:
Either<Type, ParseError>
where ParseError
is defined as follows (simplified):
interface ParseError { readonly _tag: "ParseError" readonly issue: ParseIssue}
In this structure, ParseIssue
represents an error that might occur during the parsing process.
It is wrapped in a tagged error to make it easier to catch errors using Effect.catchTag.
The result Either<Type, ParseError>
contains the inferred data type described by the schema (Type
).
A successful parse yields a Right
value with the parsed data Type
, while a failed parse results in a Left
value containing a ParseError
.
The following options affect both decoding and encoding.
When using a schema to parse a value, by default any properties that are not specified in the schema will be stripped out from the output. This is because the schema is expecting a specific shape for the parsed value, and any excess properties do not conform to that shape.
However, you can use the onExcessProperty
option (default value: "ignore"
) to trigger a parsing error. This can be particularly useful in cases where you need to detect and handle potential errors or unexpected values.
Example (onExcessProperty
set to "error"
)
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})7
8namespace 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(9 import Schema
Schema.(alias) decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync
decodeUnknownSync(const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person)({10 (property) name: string
name: "Bob",11 (property) age: number
age: 40,12 (property) email: string
email: "bob@example.com"13 })14)15/*16Output:17{ name: 'Bob', age: 40 }18*/19
20import Schema
Schema.(alias) decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync
decodeUnknownSync(const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person)(21 {22 (property) name: string
name: "Bob",23 (property) age: number
age: 40,24 (property) email: string
email: "bob@example.com"25 },26 { (property) ParseOptions.onExcessProperty?: "ignore" | "error" | "preserve" | undefined
When using a `Schema` to parse a value, by default any properties that are
not specified in the `Schema` will be stripped out from the output. This is
because the `Schema` is expecting a specific shape for the parsed value,
and any excess properties do not conform to that shape.
However, you can use the `onExcessProperty` option (default value:
`"ignore"`) to trigger a parsing error. This can be particularly useful in
cases where you need to detect and handle potential errors or unexpected
values.
If you want to allow excess properties to remain, you can use
`onExcessProperty` set to `"preserve"`.
default: "ignore"
onExcessProperty: "error" }27)28/*29throws30ParseError: { readonly name: string; readonly age: number }31└─ ["email"]32 └─ is unexpected, expected: "name" | "age"33*/
If you want to allow excess properties to remain, you can use onExcessProperty
set to "preserve"
.
Example (onExcessProperty
set to "preserve"
)
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})7
8namespace 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(9 import Schema
Schema.(alias) decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync
decodeUnknownSync(const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person)(10 {11 (property) name: string
name: "Bob",12 (property) age: number
age: 40,13 (property) email: string
email: "bob@example.com"14 },15 { (property) ParseOptions.onExcessProperty?: "ignore" | "error" | "preserve" | undefined
When using a `Schema` to parse a value, by default any properties that are
not specified in the `Schema` will be stripped out from the output. This is
because the `Schema` is expecting a specific shape for the parsed value,
and any excess properties do not conform to that shape.
However, you can use the `onExcessProperty` option (default value:
`"ignore"`) to trigger a parsing error. This can be particularly useful in
cases where you need to detect and handle potential errors or unexpected
values.
If you want to allow excess properties to remain, you can use
`onExcessProperty` set to `"preserve"`.
default: "ignore"
onExcessProperty: "preserve" }16 )17)18/*19{ email: 'bob@example.com', name: 'Bob', age: 40 }20*/
The errors
option allows you to receive all parsing errors when attempting to parse a value using a schema. By default only the first error is returned, but by setting the errors
option to "all"
, you can receive all errors that occurred during the parsing process. This can be useful for debugging or for providing more comprehensive error messages to the user.
Example (errors
set to "all"
)
1import { import Schema
Schema } from "effect"2
3const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,5 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number6})7
8import Schema
Schema.(alias) decodeUnknownSync<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly name: string;
readonly age: number;
}
export decodeUnknownSync
decodeUnknownSync(const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person)(9 {10 (property) name: string
name: "Bob",11 (property) age: string
age: "abc",12 (property) email: string
email: "bob@example.com"13 },14 { (property) ParseOptions.errors?: "first" | "all" | undefined
The `errors` option allows you to receive all parsing errors when
attempting to parse a value using a schema. By default only the first error
is returned, but by setting the `errors` option to `"all"`, you can receive
all errors that occurred during the parsing process. This can be useful for
debugging or for providing more comprehensive error messages to the user.
default: "first"
errors: "all", (property) ParseOptions.onExcessProperty?: "ignore" | "error" | "preserve" | undefined
When using a `Schema` to parse a value, by default any properties that are
not specified in the `Schema` will be stripped out from the output. This is
because the `Schema` is expecting a specific shape for the parsed value,
and any excess properties do not conform to that shape.
However, you can use the `onExcessProperty` option (default value:
`"ignore"`) to trigger a parsing error. This can be particularly useful in
cases where you need to detect and handle potential errors or unexpected
values.
If you want to allow excess properties to remain, you can use
`onExcessProperty` set to `"preserve"`.
default: "ignore"
onExcessProperty: "error" }15)16/*17throws18ParseError: { readonly name: string; readonly age: number }19├─ ["email"]20│ └─ is unexpected, expected: "name" | "age"21└─ ["age"]22 └─ Expected number, actual "abc"23*/
The propertyOrder
option provides control over the order of object fields in the output. This feature is particularly useful when the sequence of keys is important for the consuming processes or when maintaining the input order enhances readability and usability.
By default, the propertyOrder
option is set to "none"
. This means that the internal system decides the order of keys to optimize parsing speed.
The order of keys in this mode should not be considered stable, and it’s recommended not to rely on key ordering as it may change in future updates.
Setting propertyOrder
to "original"
ensures that the keys are ordered as they appear in the input during the decoding/encoding process.
Example (Synchronous Decoding)
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Struct<{
a: typeof Schema.Number;
b: Schema.Literal<["b"]>;
c: typeof Schema.Number;
}>
schema = import Schema
Schema.function Struct<{
a: typeof Schema.Number;
b: Schema.Literal<["b"]>;
c: typeof Schema.Number;
}>(fields: {
a: typeof Schema.Number;
b: Schema.Literal<["b"]>;
c: typeof Schema.Number;
}): Schema.Struct<...> (+1 overload)
namespace Struct
Struct({4 (property) a: typeof Schema.Number
a: import Schema
Schema.(alias) class Number
export Number
Number,5 (property) b: Schema.Literal<["b"]>
b: import Schema
Schema.function Literal<["b"]>(literals_0: "b"): Schema.Literal<["b"]> (+2 overloads)
Literal("b"),6 (property) c: typeof Schema.Number
c: import Schema
Schema.(alias) class Number
export Number
Number7})8
9// Decoding an object synchronously without specifying the property order10namespace 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<{
readonly a: number;
readonly b: "b";
readonly c: number;
}, {
readonly a: number;
readonly b: "b";
readonly c: number;
}>(schema: Schema.Schema<{
readonly a: number;
readonly b: "b";
readonly c: number;
}, {
readonly a: number;
readonly b: "b";
readonly c: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly a: number;
readonly b: "b";
readonly c: number;
}
export decodeUnknownSync
decodeUnknownSync(const schema: Schema.Struct<{
a: typeof Schema.Number;
b: Schema.Literal<["b"]>;
c: typeof Schema.Number;
}>
schema)({ (property) b: string
b: "b", (property) c: number
c: 2, (property) a: number
a: 1 }))11// Output decided internally: { a: 1, b: 'b', c: 2 }12
13// Decoding an object synchronously while preserving the order of properties as in the input14namespace 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(15 import Schema
Schema.(alias) decodeUnknownSync<{
readonly a: number;
readonly b: "b";
readonly c: number;
}, {
readonly a: number;
readonly b: "b";
readonly c: number;
}>(schema: Schema.Schema<{
readonly a: number;
readonly b: "b";
readonly c: number;
}, {
readonly a: number;
readonly b: "b";
readonly c: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly a: number;
readonly b: "b";
readonly c: number;
}
export decodeUnknownSync
decodeUnknownSync(const schema: Schema.Struct<{
a: typeof Schema.Number;
b: Schema.Literal<["b"]>;
c: typeof Schema.Number;
}>
schema)(16 { (property) b: string
b: "b", (property) c: number
c: 2, (property) a: number
a: 1 },17 { (property) ParseOptions.propertyOrder?: "none" | "original" | undefined
The `propertyOrder` option provides control over the order of object fields
in the output. This feature is particularly useful when the sequence of
keys is important for the consuming processes or when maintaining the input
order enhances readability and usability.
By default, the `propertyOrder` option is set to `"none"`. This means that
the internal system decides the order of keys to optimize parsing speed.
The order of keys in this mode should not be considered stable, and it's
recommended not to rely on key ordering as it may change in future updates
without notice.
Setting `propertyOrder` to `"original"` ensures that the keys are ordered
as they appear in the input during the decoding/encoding process.
default: "none"
propertyOrder: "original" }18 )19)20// Output preserving input order: { b: 'b', c: 2, a: 1 }
Example (Asynchronous Decoding)
1import type { import Duration
Duration } from "effect"2import { import Effect
Effect, import ParseResult
ParseResult, import Schema
Schema } from "effect"3
4// Function to simulate an asynchronous process within the schema5const const effectify: (duration: Duration.DurationInput) => Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>
effectify = ((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) =>6 import Schema
Schema.(alias) class Number
export Number
Number.(method) Pipeable.pipe<typeof Schema.Number, Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>>(this: typeof Schema.Number, ab: (_: typeof Schema.Number) => Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>): Schema.transformOrFail<...> (+21 overloads)
pipe(7 import Schema
Schema.const transformOrFail: <typeof Schema.Number, typeof Schema.Number, never, never>(to: typeof Schema.Number, options: {
readonly decode: (fromA: number, options: ParseOptions, ast: Transformation, fromI: number) => Effect.Effect<...>;
readonly encode: (toI: number, options: ParseOptions, ast: Transformation, toA: number) => Effect.Effect<...>;
readonly strict?: true;
} | {
...;
}) => (from: typeof Schema.Number) => Schema.transformOrFail<...> (+1 overload)
Create a new `Schema` by transforming the input and output of an existing `Schema`
using the provided decoding functions.
transformOrFail(import Schema
Schema.(alias) class Number
export Number
Number, {8 (property) strict?: true
strict: true,9 (property) decode: (fromA: number, options: ParseOptions, ast: Transformation, fromI: number) => Effect.Effect<number, ParseResult.ParseIssue, never>
decode: ((parameter) x: number
x) =>10 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).(method) Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<number, ParseResult.ParseIssue, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<...>): Effect.Effect<...> (+21 overloads)
pipe(11 import Effect
Effect.const andThen: <Either<number, ParseResult.ParseIssue>>(f: Either<number, ParseResult.ParseIssue>) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<...> (+3 overloads)
Executes a sequence of two actions, typically two `Effect`s, where the second action can depend on the result of the first action.
The `that` action can take various forms:
- a value
- a function returning a value
- a promise
- a function returning a promise
- an effect
- a function returning an effect
andThen(import ParseResult
ParseResult.const succeed: <number>(a: number) => Either<number, ParseResult.ParseIssue>
succeed((parameter) x: number
x))12 ),13 (property) encode: (toI: number, options: ParseOptions, ast: Transformation, toA: number) => Effect.Effect<number, ParseResult.ParseIssue, never>
encode: import ParseResult
ParseResult.const succeed: <A>(a: A) => Either<A, ParseResult.ParseIssue>
succeed14 })15 )16
17// Define a structure with asynchronous behavior in each field18const const schema: Schema.Struct<{
a: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>;
b: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>;
c: Schema.transformOrFail<...>;
}>
schema = import Schema
Schema.function Struct<{
a: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>;
b: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>;
c: Schema.transformOrFail<...>;
}>(fields: {
...;
}): Schema.Struct<...> (+1 overload)
namespace Struct
Struct({19 (property) a: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>
a: const effectify: (duration: Duration.DurationInput) => Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>
effectify("200 millis"),20 (property) b: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>
b: const effectify: (duration: Duration.DurationInput) => Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>
effectify("300 millis"),21 (property) c: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>
c: const effectify: (duration: Duration.DurationInput) => Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>
effectify("100 millis")22}).(method) Struct<{ a: transformOrFail<typeof Number$, typeof Number$, never>; b: transformOrFail<typeof Number$, typeof Number$, never>; c: transformOrFail<typeof Number$, typeof Number$, never>; }>.annotations(annotations: Schema.Annotations.Schema<{
readonly a: number;
readonly b: number;
readonly c: number;
}, readonly []>): Schema.Struct<{
a: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>;
b: Schema.transformOrFail<...>;
c: Schema.transformOrFail<...>;
}>
Merges a set of new annotations with existing ones, potentially overwriting
any duplicates.
annotations({ (property) Annotations.Schema<{ readonly a: number; readonly b: number; readonly c: number; }, readonly []>.concurrency?: ConcurrencyAnnotation
concurrency: 3 })23
24// Decoding data asynchronously without preserving order25import Schema
Schema.const decode: <{
readonly a: number;
readonly b: number;
readonly c: number;
}, {
readonly a: number;
readonly b: number;
readonly c: number;
}, never>(schema: Schema.Schema<{
readonly a: number;
readonly b: number;
readonly c: number;
}, {
...;
}, never>, options?: ParseOptions) => (i: {
...;
}, overrideOptions?: ParseOptions) => Effect.Effect<...>
decode(const schema: Schema.Struct<{
a: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>;
b: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>;
c: Schema.transformOrFail<...>;
}>
schema)({ (property) a: number
a: 1, (property) b: number
b: 2, (property) c: number
c: 3 })26 .(method) Pipeable.pipe<Effect.Effect<{
readonly a: number;
readonly b: number;
readonly c: number;
}, ParseResult.ParseError, never>, Promise<{
readonly a: number;
readonly b: number;
readonly c: number;
}>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Promise<...>): Promise<...> (+21 overloads)
pipe(import Effect
Effect.const runPromise: <A, E>(effect: Effect.Effect<A, E, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<A>
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)27 .(method) Promise<{ readonly a: number; readonly b: number; readonly c: number; }>.then<void, never>(onfulfilled?: ((value: {
readonly a: number;
readonly b: number;
readonly c: number;
}) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(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)28// Output decided internally: { c: 3, a: 1, b: 2 }29
30// Decoding data asynchronously while preserving the original input order31import Schema
Schema.const decode: <{
readonly a: number;
readonly b: number;
readonly c: number;
}, {
readonly a: number;
readonly b: number;
readonly c: number;
}, never>(schema: Schema.Schema<{
readonly a: number;
readonly b: number;
readonly c: number;
}, {
...;
}, never>, options?: ParseOptions) => (i: {
...;
}, overrideOptions?: ParseOptions) => Effect.Effect<...>
decode(const schema: Schema.Struct<{
a: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>;
b: Schema.transformOrFail<typeof Schema.Number, typeof Schema.Number, never>;
c: Schema.transformOrFail<...>;
}>
schema)({ (property) a: number
a: 1, (property) b: number
b: 2, (property) c: number
c: 3 }, { (property) ParseOptions.propertyOrder?: "none" | "original" | undefined
The `propertyOrder` option provides control over the order of object fields
in the output. This feature is particularly useful when the sequence of
keys is important for the consuming processes or when maintaining the input
order enhances readability and usability.
By default, the `propertyOrder` option is set to `"none"`. This means that
the internal system decides the order of keys to optimize parsing speed.
The order of keys in this mode should not be considered stable, and it's
recommended not to rely on key ordering as it may change in future updates
without notice.
Setting `propertyOrder` to `"original"` ensures that the keys are ordered
as they appear in the input during the decoding/encoding process.
default: "none"
propertyOrder: "original" })32 .(method) Pipeable.pipe<Effect.Effect<{
readonly a: number;
readonly b: number;
readonly c: number;
}, ParseResult.ParseError, never>, Promise<{
readonly a: number;
readonly b: number;
readonly c: number;
}>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<...>) => Promise<...>): Promise<...> (+21 overloads)
pipe(import Effect
Effect.const runPromise: <A, E>(effect: Effect.Effect<A, E, never>, options?: {
readonly signal?: AbortSignal;
} | undefined) => Promise<A>
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)33 .(method) Promise<{ readonly a: number; readonly b: number; readonly c: number; }>.then<void, never>(onfulfilled?: ((value: {
readonly a: number;
readonly b: number;
readonly c: number;
}) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<...>) | null | undefined): Promise<...>
Attaches callbacks for the resolution and/or rejection of the Promise.
then(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)34// Output preserving input order: { a: 1, b: 2, c: 3 }
You can tailor parse options for each schema using the parseOptions
annotation.
These options allow for specific parsing behavior at various levels of the schema hierarchy, overriding any parent settings and cascading down to nested schemas.
Example
1import { import Schema
Schema } from "effect"2import { import Either
Either } from "effect"3
4const const schema: Schema.Struct<{
a: Schema.Struct<{
b: typeof Schema.String;
c: typeof Schema.String;
}>;
d: typeof Schema.String;
}>
schema = import Schema
Schema.function Struct<{
a: Schema.Struct<{
b: typeof Schema.String;
c: typeof Schema.String;
}>;
d: typeof Schema.String;
}>(fields: {
a: Schema.Struct<{
b: typeof Schema.String;
c: typeof Schema.String;
}>;
d: typeof Schema.String;
}): Schema.Struct<...> (+1 overload)
namespace Struct
Struct({5 (property) a: Schema.Struct<{
b: typeof Schema.String;
c: typeof Schema.String;
}>
a: import Schema
Schema.function Struct<{
b: typeof Schema.String;
c: typeof Schema.String;
}>(fields: {
b: typeof Schema.String;
c: typeof Schema.String;
}): Schema.Struct<{
b: typeof Schema.String;
c: typeof Schema.String;
}> (+1 overload)
namespace Struct
Struct({6 (property) b: typeof Schema.String
b: import Schema
Schema.(alias) class String
export String
String,7 (property) c: typeof Schema.String
c: import Schema
Schema.(alias) class String
export String
String8 }).(method) Struct<{ b: typeof String$; c: typeof String$; }>.annotations(annotations: Schema.Annotations.Schema<{
readonly b: string;
readonly c: string;
}, readonly []>): Schema.Struct<{
b: typeof Schema.String;
c: typeof Schema.String;
}>
Merges a set of new annotations with existing ones, potentially overwriting
any duplicates.
annotations({9 (property) Annotations.Doc<{ readonly b: string; readonly c: string; }>.title?: string
title: "first error only",10 // Only the first error in this sub-schema is reported11 (property) Annotations.Schema<{ readonly b: string; readonly c: string; }, readonly []>.parseOptions?: ParseOptions
parseOptions: { (property) ParseOptions.errors?: "first" | "all" | undefined
The `errors` option allows you to receive all parsing errors when
attempting to parse a value using a schema. By default only the first error
is returned, but by setting the `errors` option to `"all"`, you can receive
all errors that occurred during the parsing process. This can be useful for
debugging or for providing more comprehensive error messages to the user.
default: "first"
errors: "first" }12 }),13 (property) d: typeof Schema.String
d: import Schema
Schema.(alias) class String
export String
String14}).(method) Struct<{ a: Struct<{ b: typeof String$; c: typeof String$; }>; d: typeof String$; }>.annotations(annotations: Schema.Annotations.Schema<{
readonly a: {
readonly b: string;
readonly c: string;
};
readonly d: string;
}, readonly []>): Schema.Struct<{
a: Schema.Struct<{
b: typeof Schema.String;
c: typeof Schema.String;
}>;
d: typeof Schema.String;
}>
Merges a set of new annotations with existing ones, potentially overwriting
any duplicates.
annotations({15 (property) Annotations.Doc<A>.title?: string
title: "all errors",16 // All errors in the main schema are reported17 (property) Annotations.Schema<A, TypeParameters extends ReadonlyArray<any> = readonly []>.parseOptions?: ParseOptions
parseOptions: { (property) ParseOptions.errors?: "first" | "all" | undefined
The `errors` option allows you to receive all parsing errors when
attempting to parse a value using a schema. By default only the first error
is returned, but by setting the `errors` option to `"all"`, you can receive
all errors that occurred during the parsing process. This can be useful for
debugging or for providing more comprehensive error messages to the user.
default: "first"
errors: "all" }18})19
20const const result: Either.Either<{
readonly a: {
readonly b: string;
readonly c: string;
};
readonly d: string;
}, ParseError>
result = import Schema
Schema.const decodeUnknownEither: <{
readonly a: {
readonly b: string;
readonly c: string;
};
readonly d: string;
}, {
readonly a: {
readonly b: string;
readonly c: string;
};
readonly d: string;
}>(schema: Schema.Schema<{
readonly a: {
readonly b: string;
readonly c: string;
};
readonly d: string;
}, {
...;
}, never>, options?: ParseOptions) => (u: unknown, overrideOptions?: ParseOptions) => Either.Either<...>
decodeUnknownEither(const schema: Schema.Struct<{
a: Schema.Struct<{
b: typeof Schema.String;
c: typeof Schema.String;
}>;
d: typeof Schema.String;
}>
schema)(21 { (property) a: {}
a: {} },22 { (property) ParseOptions.errors?: "first" | "all" | undefined
The `errors` option allows you to receive all parsing errors when
attempting to parse a value using a schema. By default only the first error
is returned, but by setting the `errors` option to `"all"`, you can receive
all errors that occurred during the parsing process. This can be useful for
debugging or for providing more comprehensive error messages to the user.
default: "first"
errors: "first" }23)24if (import Either
Either.const isLeft: <{
readonly a: {
readonly b: string;
readonly c: string;
};
readonly d: string;
}, ParseError>(self: Either.Either<{
readonly a: {
readonly b: string;
readonly c: string;
};
readonly d: string;
}, ParseError>) => self is Either.Left<...>
Determine if a `Either` is a `Left`.
isLeft(const result: Either.Either<{
readonly a: {
readonly b: string;
readonly c: string;
};
readonly d: string;
}, ParseError>
result)) {25 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 result: Either.Left<ParseError, {
readonly a: {
readonly b: string;
readonly c: string;
};
readonly d: string;
}>
result.(property) Left<ParseError, { readonly a: { readonly b: string; readonly c: string; }; readonly d: string; }>.left: ParseError
left.(property) ParseError.message: string
message)26}27/*28all errors29├─ ["a"]30│ └─ first error only31│ └─ ["b"]32│ └─ is missing33└─ ["d"]34 └─ is missing35*/
Detailed Output Explanation:
In this example:
- The main schema is configured to display all errors. Hence, you will see errors related to both the
d
field (since it’s missing) and any errors from thea
subschema. - The subschema (
a
) is set to display only the first error. Although bothb
andc
fields are missing, only the first missing field (b
) is reported.
The Schema.is
function provides a way to verify if a value conforms to a given schema. It acts as a type guard, taking a value of type unknown
and determining if it matches the structure and type constraints defined in the schema.
Here’s how the Schema.is
function works:
-
Schema Definition: Define a schema to describe the structure and constraints of the data type you expect. For instance,
Schema<Type, Encoded, Context>
, whereType
is the target type you want to validate against. -
Type Guard Creation: Use the schema to create a user-defined type guard,
(u: unknown) => u is Type
. This function can be used at runtime to check if a value meets the requirements of the schema.
Example (Creating and Using a Type Guard)
1import { import Schema
Schema } from "effect"2
3// Define a schema for a Person object4const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({5 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,6 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number7})8
9// Create a type guard using the schema10const const isPerson: (u: unknown, overrideOptions?: ParseOptions | number) => u is {
readonly name: string;
readonly age: number;
}
isPerson = import Schema
Schema.(alias) is<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions | number) => u is {
readonly name: string;
readonly age: number;
}
export is
By default the option `exact` is set to `true`.
is(const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person)11
12// Test the type guard with different values13namespace 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 isPerson: (u: unknown, overrideOptions?: ParseOptions | number) => u is {
readonly name: string;
readonly age: number;
}
isPerson({ (property) name: string
name: "Alice", (property) age: number
age: 30 })) // true14namespace 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 isPerson: (u: unknown, overrideOptions?: ParseOptions | number) => u is {
readonly name: string;
readonly age: number;
}
isPerson(null)) // false15namespace 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 isPerson: (u: unknown, overrideOptions?: ParseOptions | number) => u is {
readonly name: string;
readonly age: number;
}
isPerson({})) // false
The isPerson
function generated from the schema has the following signature:
const isPerson: ( u: unknown, overrideOptions?: number | ParseOptions) => u is { readonly name: string readonly age: number}
While type guards verify whether a value conforms to a specific type, the Schema.asserts
function goes further by asserting that an input matches the schema type Type
(from Schema<Type, Encoded, Context>
).
If the input does not match the schema, it throws a detailed error, making it useful for runtime validation.
Example (Creating and Using an Assertion)
1import { import Schema
Schema } from "effect"2
3// Define a schema for a Person object4const const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person = import Schema
Schema.function Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({5 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,6 (property) age: typeof Schema.Number
age: import Schema
Schema.(alias) class Number
export Number
Number7})8
9// Create an assertion function from the schema10const const assertsPerson: Schema.Schema.ToAsserts<Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>>
assertsPerson: import Schema
Schema.namespace Schema
Schema.type Schema<in out A, in out I = A, out R = never>.ToAsserts<S extends Schema.Schema.AnyNoContext> = (input: unknown, options?: ParseOptions) => asserts input is Schema.Schema.Type<S>
ToAsserts<typeof const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person> =11 import Schema
Schema.(alias) asserts<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>(schema: Schema.Schema<{
readonly name: string;
readonly age: number;
}, {
readonly name: string;
readonly age: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => asserts u is {
readonly name: string;
readonly age: number;
}
export asserts
By default the option `exact` is set to `true`.
asserts(const Person: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
Person)12
13try {14 // Attempt to assert that the input matches the Person schema15 const assertsPerson: (input: unknown, options?: ParseOptions) => asserts input is Schema.Schema<in out A, in out I = A, out R = never>.Type<Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>>
assertsPerson({ (property) name: string
name: "Alice", (property) age: string
age: "30" })16} catch (var e: unknown
e) {17 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.error(message?: any, ...optionalParams: any[]): void
Prints to `stderr` 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
```
If formatting elements (e.g. `%d`) are not found in the first string then
[`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
for more information.
error("The input does not match the schema:")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.error(message?: any, ...optionalParams: any[]): void
Prints to `stderr` 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
```
If formatting elements (e.g. `%d`) are not found in the first string then
[`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
for more information.
error(var e: unknown
e)19}20/*21throws:22The input does not match the schema:23{24 _id: 'ParseError',25 message: '{ readonly name: string; readonly age: number }\n' +26 '└─ ["age"]\n' +27 ' └─ Expected number, actual "30"'28}29*/30
31// This input matches the schema and will not throw an error32const assertsPerson: (input: unknown, options?: ParseOptions) => asserts input is Schema.Schema<in out A, in out I = A, out R = never>.Type<Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>>
assertsPerson({ (property) name: string
name: "Alice", (property) age: number
age: 30 })
The assertsPerson
function generated from the schema has the following signature:
const assertsPerson: ( input: unknown, overrideOptions?: number | ParseOptions) => asserts input is { readonly name: string readonly age: number}
When decoding, it’s important to understand how missing properties are processed. By default, if a property is not present in the input, it is treated as if it were present with an undefined
value.
Example (Default Behavior)
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Struct<{
a: typeof Schema.Unknown;
}>
schema = import Schema
Schema.function Struct<{
a: typeof Schema.Unknown;
}>(fields: {
a: typeof Schema.Unknown;
}): Schema.Struct<{
a: typeof Schema.Unknown;
}> (+1 overload)
namespace Struct
Struct({ (property) a: typeof Schema.Unknown
a: import Schema
Schema.class Unknown
Unknown })4const const input: {}
input = {}5
6namespace 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<{
readonly a: unknown;
}, {
readonly a: unknown;
}>(schema: Schema.Schema<{
readonly a: unknown;
}, {
readonly a: unknown;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly a: unknown;
}
export decodeUnknownSync
decodeUnknownSync(const schema: Schema.Struct<{
a: typeof Schema.Unknown;
}>
schema)(const input: {}
input))7// Output: { a: undefined }
In this example, although the key "a"
is not present in the input, it is treated as { a: undefined }
by default.
If your validation logic needs to distinguish between truly missing properties and those that are explicitly undefined, you can enable the exact
option:
Example (exact
set to true
)
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Struct<{
a: typeof Schema.Unknown;
}>
schema = import Schema
Schema.function Struct<{
a: typeof Schema.Unknown;
}>(fields: {
a: typeof Schema.Unknown;
}): Schema.Struct<{
a: typeof Schema.Unknown;
}> (+1 overload)
namespace Struct
Struct({ (property) a: typeof Schema.Unknown
a: import Schema
Schema.class Unknown
Unknown })4const const input: {}
input = {}5
6namespace 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<{
readonly a: unknown;
}, {
readonly a: unknown;
}>(schema: Schema.Schema<{
readonly a: unknown;
}, {
readonly a: unknown;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly a: unknown;
}
export decodeUnknownSync
decodeUnknownSync(const schema: Schema.Struct<{
a: typeof Schema.Unknown;
}>
schema)(const input: {}
input, { (property) ParseOptions.exact?: boolean | undefined
Handles missing properties in data structures. By default, missing
properties are treated as if present with an `undefined` value. To treat
missing properties as errors, set the `exact` option to `true`. This
setting is already enabled by default for `is` and `asserts` functions,
treating absent properties strictly unless overridden.
default: false
exact: true }))7/*8throws9ParseError: { readonly a: unknown }10└─ ["a"]11 └─ is missing12*/
For the APIs Schema.is
and Schema.asserts
, however, the default behavior is to treat missing properties strictly, where the default for exact
is true
:
Example (Default Behavior for Schema.is
and Schema.asserts
)
1import type { import SchemaAST
SchemaAST } from "effect"2import { import Schema
Schema } from "effect"3
4const const schema: Schema.Struct<{
a: typeof Schema.Unknown;
}>
schema = import Schema
Schema.function Struct<{
a: typeof Schema.Unknown;
}>(fields: {
a: typeof Schema.Unknown;
}): Schema.Struct<{
a: typeof Schema.Unknown;
}> (+1 overload)
namespace Struct
Struct({ (property) a: typeof Schema.Unknown
a: import Schema
Schema.class Unknown
Unknown })5const const input: {}
input = {}6
7namespace 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) is<{
readonly a: unknown;
}, {
readonly a: unknown;
}, never>(schema: Schema.Schema<{
readonly a: unknown;
}, {
readonly a: unknown;
}, never>, options?: SchemaAST.ParseOptions): (u: unknown, overrideOptions?: SchemaAST.ParseOptions | number) => u is {
readonly a: unknown;
}
export is
By default the option `exact` is set to `true`.
is(const schema: Schema.Struct<{
a: typeof Schema.Unknown;
}>
schema)(const input: {}
input)) // Output: false8namespace 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) is<{
readonly a: unknown;
}, {
readonly a: unknown;
}, never>(schema: Schema.Schema<{
readonly a: unknown;
}, {
readonly a: unknown;
}, never>, options?: SchemaAST.ParseOptions): (u: unknown, overrideOptions?: SchemaAST.ParseOptions | number) => u is {
readonly a: unknown;
}
export is
By default the option `exact` is set to `true`.
is(const schema: Schema.Struct<{
a: typeof Schema.Unknown;
}>
schema)(const input: {}
input, { (property) ParseOptions.exact?: boolean | undefined
Handles missing properties in data structures. By default, missing
properties are treated as if present with an `undefined` value. To treat
missing properties as errors, set the `exact` option to `true`. This
setting is already enabled by default for `is` and `asserts` functions,
treating absent properties strictly unless overridden.
default: false
exact: false })) // Output: true9
10const const asserts: (u: unknown, overrideOptions?: SchemaAST.ParseOptions) => asserts u is {
readonly a: unknown;
}
asserts: (11 (parameter) u: unknown
u: unknown,12 (parameter) overrideOptions: SchemaAST.ParseOptions | undefined
overrideOptions?: import SchemaAST
SchemaAST.interface ParseOptions
ParseOptions13) => asserts (parameter) u: unknown
u is {14 readonly (property) a: unknown
a: unknown15} = import Schema
Schema.(alias) asserts<{
readonly a: unknown;
}, {
readonly a: unknown;
}, never>(schema: Schema.Schema<{
readonly a: unknown;
}, {
readonly a: unknown;
}, never>, options?: SchemaAST.ParseOptions): (u: unknown, overrideOptions?: SchemaAST.ParseOptions) => asserts u is {
readonly a: unknown;
}
export asserts
By default the option `exact` is set to `true`.
asserts(const schema: Schema.Struct<{
a: typeof Schema.Unknown;
}>
schema)16
17try {18 const asserts: (u: unknown, overrideOptions?: SchemaAST.ParseOptions) => asserts u is {
readonly a: unknown;
}
asserts(const input: {}
input)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("asserts passed")20} catch (var e: any
e: any) {21 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.error(message?: any, ...optionalParams: any[]): void
Prints to `stderr` 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
```
If formatting elements (e.g. `%d`) are not found in the first string then
[`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
for more information.
error("asserts failed")22 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.error(message?: any, ...optionalParams: any[]): void
Prints to `stderr` 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
```
If formatting elements (e.g. `%d`) are not found in the first string then
[`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
for more information.
error(var e: any
e.any
message)23}24/*25Output:26asserts failed27{ readonly a: unknown }28└─ ["a"]29 └─ is missing30*/31
32try {33 const asserts: (u: unknown, overrideOptions?: SchemaAST.ParseOptions) => asserts u is {
readonly a: unknown;
}
asserts(const input: {}
input, { (property) ParseOptions.exact?: boolean | undefined
Handles missing properties in data structures. By default, missing
properties are treated as if present with an `undefined` value. To treat
missing properties as errors, set the `exact` option to `true`. This
setting is already enabled by default for `is` and `asserts` functions,
treating absent properties strictly unless overridden.
default: false
exact: false })34 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("asserts passed")35} catch (var e: any
e: any) {36 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.error(message?: any, ...optionalParams: any[]): void
Prints to `stderr` 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
```
If formatting elements (e.g. `%d`) are not found in the first string then
[`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
for more information.
error("asserts failed")37 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.error(message?: any, ...optionalParams: any[]): void
Prints to `stderr` 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 code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
```
If formatting elements (e.g. `%d`) are not found in the first string then
[`util.inspect()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilinspectobject-options) is called on each argument and the
resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)
for more information.
error(var e: any
e.any
message)38}39// Output: asserts passed
The naming conventions in effect/Schema
are designed to be straightforward and logical, focusing primarily on compatibility with JSON serialization. This approach simplifies the understanding and use of schemas, especially for developers who are integrating web technologies where JSON is a standard data interchange format.
JSON-Compatible Types
Schemas that naturally serialize to JSON-compatible formats are named directly after their data types.
For instance:
Schema.Date
: serializes JavaScript Date objects to ISO-formatted strings, a typical method for representing dates in JSON.Schema.Number
: used directly as it maps precisely to the JSON number type, requiring no special transformation to remain JSON-compatible.
Non-JSON-Compatible Types
When dealing with types that do not have a direct representation in JSON, the naming strategy incorporates additional details to indicate the necessary transformation. This helps in setting clear expectations about the schema’s behavior:
For instance:
Schema.DateFromSelf
: indicates that the schema handlesDate
objects, which are not natively JSON-serializable.Schema.NumberFromString
: this naming suggests that the schema processes numbers that are initially represented as strings, emphasizing the transformation from string to number when decoding.
The primary goal of these schemas is to ensure that domain objects can be easily serialized (“encoded”) and deserialized (“decoded”) for transmission over network connections, thus facilitating their transfer between different parts of an application or across different applications.
While JSON’s ubiquity justifies its primary consideration in naming, the conventions also accommodate serialization for other types of transport. For instance, converting a Date
to a string is a universally useful method for various communication protocols, not just JSON. Thus, the selected naming conventions serve as sensible defaults that prioritize clarity and ease of use, facilitating the serialization and deserialization processes across diverse technological environments.