Basic Usage
The Schema
module provides built-in schemas for common primitive types.
Schema | Equivalent TypeScript Type |
---|---|
Schema.String | string |
Schema.Number | number |
Schema.Boolean | boolean |
Schema.BigIntFromSelf | BigInt |
Schema.SymbolFromSelf | symbol |
Schema.Object | object |
Schema.Undefined | undefined |
Schema.Void | void |
Schema.Any | any |
Schema.Unknown | unknown |
Schema.Never | never |
Example
1import { import Schema
Schema } from "effect"2
3const const schema: typeof Schema.String
schema = import Schema
Schema.(alias) class String
export String
String4
5// string6type type Type = string
Type = typeof const schema: typeof Schema.String
schema.(property) Schema<string, string, never>.Type: string
Type
To make it easier to work with schemas, built-in schemas are exposed with shorter, opaque types when possible.
The Schema.asSchema
function allows you to view any schema as Schema<Type, Encoded, Context>
.
Example
For example, while Schema.String
is defined as a class with a type of typeof Schema.String
, using Schema.asSchema
provides the schema in its extended form as Schema<string, string, never>
.
1import { import Schema
Schema } from "effect"2
3// The original schema type: typeof Schema.String4const const schema: typeof Schema.String
schema = import Schema
Schema.(alias) class String
export String
String5
6// Using asSchema to view it as Schema<string, string, never>7const const nomalized: Schema.Schema<string, string, never>
nomalized = import Schema
Schema.const asSchema: <typeof Schema.String>(schema: typeof Schema.String) => Schema.Schema<string, string, never>
asSchema(const schema: typeof Schema.String
schema)
You can create a schema for unique symbols using Schema.UniqueSymbolFromSelf
.
1import { import Schema
Schema } from "effect"2
3const const mySymbol: typeof mySymbol
mySymbol = var Symbol: SymbolConstructor
Symbol.(method) SymbolConstructor.for(key: string): symbol
Returns a Symbol object from the global symbol registry matching the given key if found.
Otherwise, returns a new symbol with this key.
for("mySymbol")4
5const const schema: Schema.SchemaClass<typeof mySymbol, typeof mySymbol, never>
schema = import Schema
Schema.const UniqueSymbolFromSelf: <typeof mySymbol>(symbol: typeof mySymbol) => Schema.SchemaClass<typeof mySymbol, typeof mySymbol, never>
UniqueSymbolFromSelf(const mySymbol: typeof mySymbol
mySymbol)6
7// typeof mySymbol8type type Type = typeof mySymbol
Type = typeof const schema: Schema.SchemaClass<typeof mySymbol, typeof mySymbol, never>
schema.(property) Schema<typeof mySymbol, typeof mySymbol, never>.Type: typeof mySymbol
Type
Literal schemas represent a literal type. You can use them to specify exact values that a type must have.
1import { import Schema
Schema } from "effect"2
3import Schema
Schema.class Null
Null // Same as S.Literal(null)4import Schema
Schema.function Literal<["a"]>(literals_0: "a"): Schema.Literal<["a"]> (+2 overloads)
Literal("a") // string literal5import Schema
Schema.function Literal<[1]>(literals_0: 1): Schema.Literal<[1]> (+2 overloads)
Literal(1) // number literal6import Schema
Schema.function Literal<[true]>(literals_0: true): Schema.Literal<[true]> (+2 overloads)
Literal(true) // boolean literal7import Schema
Schema.function Literal<[2n]>(literals_0: 2n): Schema.Literal<[2n]> (+2 overloads)
Literal(2n) // BigInt literal
You can create a union of multiple literals by passing them as arguments to the Schema.Literal
constructor:
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Literal<["a", "b", "c"]>
schema = import Schema
Schema.function Literal<["a", "b", "c"]>(literals_0: "a", literals_1: "b", literals_2: "c"): Schema.Literal<["a", "b", "c"]> (+2 overloads)
Literal("a", "b", "c")4
5// "a" | "b" | "c"6type type Type = "a" | "b" | "c"
Type = typeof const schema: Schema.Literal<["a", "b", "c"]>
schema.(property) Schema<"a" | "b" | "c", "a" | "b" | "c", never>.Type: "a" | "b" | "c"
Type
You can access the literals defined in a literal schema using the literals
property:
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Literal<["a", "b"]>
schema = import Schema
Schema.function Literal<["a", "b"]>(literals_0: "a", literals_1: "b"): Schema.Literal<["a", "b"]> (+2 overloads)
Literal("a", "b")4
5const const literals: readonly ["a", "b"]
literals = const schema: Schema.Literal<["a", "b"]>
schema.(property) Literal<["a", "b"]>.literals: readonly ["a", "b"]
literals6// ^? const literals: readonly ["a", "b"]
You can use Schema.pickLiteral
with a literal schema to narrow down its possible values.
1import { import Schema
Schema } from "effect"2
3// Create a schema for a subset of literals ("a" and "b") from a larger set4import Schema
Schema.function Literal<["a", "b", "c"]>(literals_0: "a", literals_1: "b", literals_2: "c"): Schema.Literal<["a", "b", "c"]> (+2 overloads)
Literal("a", "b", "c").(method) Pipeable.pipe<Schema.Literal<["a", "b", "c"]>, Schema.Literal<["a", "b"]>>(this: Schema.Literal<...>, ab: (_: Schema.Literal<["a", "b", "c"]>) => Schema.Literal<["a", "b"]>): Schema.Literal<...> (+21 overloads)
pipe(import Schema
Schema.const pickLiteral: <"a" | "b" | "c", ["a", "b"]>(literals_0: "a", literals_1: "b") => <I, R>(_schema: Schema.Schema<"a" | "b" | "c", I, R>) => Schema.Literal<["a", "b"]>
Creates a new `Schema` from a literal schema.
pickLiteral("a", "b"))
Example
Sometimes, you may need to reuse a literal schema in other parts of your code. Below is an example demonstrating how to do this:
1import { import Schema
Schema } from "effect"2
3// Define the source of truth for fruit categories4const const FruitCategory: Schema.Literal<["sweet", "citrus", "tropical"]>
FruitCategory = import Schema
Schema.function Literal<["sweet", "citrus", "tropical"]>(literals_0: "sweet", literals_1: "citrus", literals_2: "tropical"): Schema.Literal<["sweet", "citrus", "tropical"]> (+2 overloads)
Literal("sweet", "citrus", "tropical")5
6const const Fruit: Schema.Struct<{
id: typeof Schema.Number;
category: Schema.Literal<["sweet", "citrus", "tropical"]>;
}>
Fruit = import Schema
Schema.function Struct<{
id: typeof Schema.Number;
category: Schema.Literal<["sweet", "citrus", "tropical"]>;
}>(fields: {
id: typeof Schema.Number;
category: Schema.Literal<["sweet", "citrus", "tropical"]>;
}): Schema.Struct<...> (+1 overload)
namespace Struct
Struct({7 (property) id: typeof Schema.Number
id: import Schema
Schema.(alias) class Number
export Number
Number,8 (property) category: Schema.Literal<["sweet", "citrus", "tropical"]>
category: const FruitCategory: Schema.Literal<["sweet", "citrus", "tropical"]>
FruitCategory9})10
11// Create a subtype of Fruit using a subset of FruitCategory12const const SweetAndCitrusFruit: Schema.Struct<{
id: typeof Schema.Number;
category: Schema.Literal<["sweet", "citrus"]>;
}>
SweetAndCitrusFruit = import Schema
Schema.function Struct<{
id: typeof Schema.Number;
category: Schema.Literal<["sweet", "citrus"]>;
}>(fields: {
id: typeof Schema.Number;
category: Schema.Literal<["sweet", "citrus"]>;
}): Schema.Struct<...> (+1 overload)
namespace Struct
Struct({13 (property) id: typeof Schema.Number
id: import Schema
Schema.(alias) class Number
export Number
Number,14 (property) category: Schema.Literal<["sweet", "citrus"]>
category: const FruitCategory: Schema.Literal<["sweet", "citrus", "tropical"]>
FruitCategory.(method) Pipeable.pipe<Schema.Literal<["sweet", "citrus", "tropical"]>, Schema.Literal<["sweet", "citrus"]>>(this: Schema.Literal<...>, ab: (_: Schema.Literal<["sweet", "citrus", "tropical"]>) => Schema.Literal<...>): Schema.Literal<...> (+21 overloads)
pipe(import Schema
Schema.const pickLiteral: <"sweet" | "citrus" | "tropical", ["sweet", "citrus"]>(literals_0: "sweet", literals_1: "citrus") => <I, R>(_schema: Schema.Schema<"sweet" | "citrus" | "tropical", I, R>) => Schema.Literal<...>
Creates a new `Schema` from a literal schema.
pickLiteral("sweet", "citrus"))15})
In this example, FruitCategory
serves as the source of truth for the different fruit categories.
We reuse it to create a subtype of Fruit
called SweetAndCitrusFruit
, ensuring that only the specified categories ("sweet"
and "citrus"
) are allowed.
This approach helps maintain consistency throughout your code and provides type safety if the category definition changes.
In TypeScript, template literals types allow you to embed expressions within string literals.
The Schema.TemplateLiteral
constructor allows you to create a schema for these template literal types.
Example
1import { import Schema
Schema } from "effect"2
3// This creates a TemplateLiteral of type `a${string}`4import Schema
Schema.const TemplateLiteral: <["a", typeof Schema.String]>(head: "a", tail_0: typeof Schema.String) => Schema.TemplateLiteral<`a${string}`>
TemplateLiteral("a", import Schema
Schema.(alias) class String
export String
String)5
6// This creates a TemplateLiteral of type7// `https://${string}.com` | `https://${string}.net`8import Schema
Schema.const TemplateLiteral: <["https://", typeof Schema.String, ".", Schema.Literal<["com", "net"]>]>(head: "https://", tail_0: typeof Schema.String, tail_1: ".", tail_2: Schema.Literal<["com", "net"]>) => Schema.TemplateLiteral<...>
TemplateLiteral(9 "https://",10 import Schema
Schema.(alias) class String
export String
String,11 ".",12 import Schema
Schema.function Literal<["com", "net"]>(literals_0: "com", literals_1: "net"): Schema.Literal<["com", "net"]> (+2 overloads)
Literal("com", "net")13)
Example (From template literals types Documentation)
Let’s look at a more complex example. Suppose you have two sets of locale IDs for emails and footers.
You can use the Schema.TemplateLiteral
constructor to create a schema that combines these IDs:
1import { import Schema
Schema } from "effect"2
3const const EmailLocaleIDs: Schema.Literal<["welcome_email", "email_heading"]>
EmailLocaleIDs = import Schema
Schema.function Literal<["welcome_email", "email_heading"]>(literals_0: "welcome_email", literals_1: "email_heading"): Schema.Literal<["welcome_email", "email_heading"]> (+2 overloads)
Literal("welcome_email", "email_heading")4const const FooterLocaleIDs: Schema.Literal<["footer_title", "footer_sendoff"]>
FooterLocaleIDs = import Schema
Schema.function Literal<["footer_title", "footer_sendoff"]>(literals_0: "footer_title", literals_1: "footer_sendoff"): Schema.Literal<["footer_title", "footer_sendoff"]> (+2 overloads)
Literal("footer_title", "footer_sendoff")5
6// This creates a TemplateLiteral of type7// "welcome_email_id" | "email_heading_id" |8// "footer_title_id" | "footer_sendoff_id"9import Schema
Schema.const TemplateLiteral: <[Schema.Union<[Schema.Literal<["welcome_email", "email_heading"]>, Schema.Literal<["footer_title", "footer_sendoff"]>]>, "_id"]>(head: Schema.Union<[Schema.Literal<["welcome_email", "email_heading"]>, Schema.Literal<...>]>, tail_0: "_id") => Schema.TemplateLiteral<...>
TemplateLiteral(10 import Schema
Schema.function Union<[Schema.Literal<["welcome_email", "email_heading"]>, Schema.Literal<["footer_title", "footer_sendoff"]>]>(members_0: Schema.Literal<["welcome_email", "email_heading"]>, members_1: Schema.Literal<...>): Schema.Union<...> (+3 overloads)
Union(const EmailLocaleIDs: Schema.Literal<["welcome_email", "email_heading"]>
EmailLocaleIDs, const FooterLocaleIDs: Schema.Literal<["footer_title", "footer_sendoff"]>
FooterLocaleIDs),11 "_id"12)
The Schema.TemplateLiteral
constructor supports the following types of spans:
Schema.String
Schema.Number
- Literals:
string | number | boolean | null | bigint
. These can be either wrapped bySchema.Literal
or used directly - Unions of the above types
The Schema.TemplateLiteral
constructor, while useful as a simple validator, only verifies that an input conforms to a specific string pattern by converting template literal definitions into regular expressions. Similarly, Schema.pattern
employs regular expressions directly for the same purpose. Post-validation, both methods require additional manual parsing to convert the validated string into a usable data format.
To address these limitations and eliminate the need for manual post-validation parsing, the Schema.TemplateLiteralParser
API has been developed. It not only validates the input format but also automatically parses it into a more structured and type-safe output, specifically into a tuple format.
Example
1import { import Schema
Schema } from "effect"2
3// Schema<readonly [number, "a", string], `${string}a${string}`>4const const schema: Schema.TemplateLiteralParser<[typeof Schema.NumberFromString, "a", typeof Schema.NonEmptyString]>
schema = import Schema
Schema.const TemplateLiteralParser: <[typeof Schema.NumberFromString, "a", typeof Schema.NonEmptyString]>(params_0: typeof Schema.NumberFromString, params_1: "a", params_2: typeof Schema.NonEmptyString) => Schema.TemplateLiteralParser<...>
TemplateLiteralParser(5 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".
NumberFromString,6 "a",7 import Schema
Schema.class NonEmptyString
NonEmptyString8)9
10namespace 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) decodeSync<readonly [number, "a", string], `${string}a${string}`>(schema: Schema.Schema<readonly [number, "a", string], `${string}a${string}`, never>, options?: ParseOptions): (i: `${string}a${string}`, overrideOptions?: ParseOptions) => readonly [...]
export decodeSync
decodeSync(const schema: Schema.TemplateLiteralParser<[typeof Schema.NumberFromString, "a", typeof Schema.NonEmptyString]>
schema)("100afoo"))11// Output: [ 100, 'a', 'foo' ]12
13namespace 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 [number, "a", string], `${string}a${string}`>(schema: Schema.Schema<readonly [number, "a", string], `${string}a${string}`, never>, options?: ParseOptions): (a: readonly [...], overrideOptions?: ParseOptions) => `${string}a${string}`
export encodeSync
encodeSync(const schema: Schema.TemplateLiteralParser<[typeof Schema.NumberFromString, "a", typeof Schema.NonEmptyString]>
schema)([100, "a", "foo"]))14// Output: '100afoo'
The Schema
module provides support for native TypeScript enums. You can define a schema for an enum using Schema.Enums
, allowing you to validate values that belong to the enum.
Example
1import { import Schema
Schema } from "effect"2
3enum enum Fruits
Fruits {4 (enum member) Fruits.Apple = 0
Apple,5 (enum member) Fruits.Banana = 1
Banana6}7
8const const schema: Schema.Enums<typeof Fruits>
schema = import Schema
Schema.const Enums: <typeof Fruits>(enums: typeof Fruits) => Schema.Enums<typeof Fruits>
Enums(enum Fruits
Fruits)9
10// Fruits11type type Type = Fruits
Type = typeof const schema: Schema.Enums<typeof Fruits>
schema.(property) Schema<Fruits, Fruits, never>.Type: Fruits
Type
Enums are accessible through the enums
property of the schema. You can use this property to retrieve individual members or the entire set of enum values.
1import { import Schema
Schema } from "effect"2
3enum enum Fruits
Fruits {4 (enum member) Fruits.Apple = 0
Apple,5 (enum member) Fruits.Banana = 1
Banana6}7
8const const schema: Schema.Enums<typeof Fruits>
schema = import Schema
Schema.const Enums: <typeof Fruits>(enums: typeof Fruits) => Schema.Enums<typeof Fruits>
Enums(enum Fruits
Fruits)9
10const schema: Schema.Enums<typeof Fruits>
schema.(property) Enums<typeof Fruits>.enums: typeof Fruits
enums // Returns all enum members11const schema: Schema.Enums<typeof Fruits>
schema.(property) Enums<typeof Fruits>.enums: typeof Fruits
enums.(enum member) Fruits.Apple = 0
Apple // Access the Apple member12const schema: Schema.Enums<typeof Fruits>
schema.(property) Enums<typeof Fruits>.enums: typeof Fruits
enums.(enum member) Fruits.Banana = 1
Banana // Access the Banana member
The Schema
module includes a built-in Schema.Union
constructor for creating “OR” types, allowing you to define schemas that can represent multiple types.
Example
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Union<[typeof Schema.String, typeof Schema.Number]>
schema = import Schema
Schema.function Union<[typeof Schema.String, typeof Schema.Number]>(members_0: typeof Schema.String, members_1: typeof Schema.Number): Schema.Union<[typeof Schema.String, typeof Schema.Number]> (+3 overloads)
Union(import Schema
Schema.(alias) class String
export String
String, import Schema
Schema.(alias) class Number
export Number
Number)4
5// string | number6type type Type = string | number
Type = typeof const schema: Schema.Union<[typeof Schema.String, typeof Schema.Number]>
schema.(property) Schema<string | number, string | number, never>.Type: string | number
Type
While you can create a union of literals by combining individual literal schemas:
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Union<[Schema.Literal<["a"]>, Schema.Literal<["b"]>, Schema.Literal<["c"]>]>
schema = import Schema
Schema.function Union<[Schema.Literal<["a"]>, Schema.Literal<["b"]>, Schema.Literal<["c"]>]>(members_0: Schema.Literal<["a"]>, members_1: Schema.Literal<["b"]>, members_2: Schema.Literal<...>): Schema.Union<...> (+3 overloads)
Union(4 import Schema
Schema.function Literal<["a"]>(literals_0: "a"): Schema.Literal<["a"]> (+2 overloads)
Literal("a"),5 import Schema
Schema.function Literal<["b"]>(literals_0: "b"): Schema.Literal<["b"]> (+2 overloads)
Literal("b"),6 import Schema
Schema.function Literal<["c"]>(literals_0: "c"): Schema.Literal<["c"]> (+2 overloads)
Literal("c")7)
You can simplify the process by passing multiple literals directly to the Schema.Literal
constructor:
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Literal<["a", "b", "c"]>
schema = import Schema
Schema.function Literal<["a", "b", "c"]>(literals_0: "a", literals_1: "b", literals_2: "c"): Schema.Literal<["a", "b", "c"]> (+2 overloads)
Literal("a", "b", "c")4
5// "a" | "b" | "c"6type type Type = "a" | "b" | "c"
Type = typeof const schema: Schema.Literal<["a", "b", "c"]>
schema.(property) Schema<"a" | "b" | "c", "a" | "b" | "c", never>.Type: "a" | "b" | "c"
Type
The Schema
module provides utility functions to create schemas for nullable types:
1import { import Schema
Schema } from "effect"2
3// Represents a schema for a string or null value4import Schema
Schema.const NullOr: <typeof Schema.String>(self: typeof Schema.String) => Schema.NullOr<typeof Schema.String>
NullOr(import Schema
Schema.(alias) class String
export String
String)5
6// Represents a schema for a string, null, or undefined value7import Schema
Schema.const NullishOr: <typeof Schema.String>(self: typeof Schema.String) => Schema.NullishOr<typeof Schema.String>
NullishOr(import Schema
Schema.(alias) class String
export String
String)8
9// Represents a schema for a string or undefined value10import Schema
Schema.const UndefinedOr: <typeof Schema.String>(self: typeof Schema.String) => Schema.UndefinedOr<typeof Schema.String>
UndefinedOr(import Schema
Schema.(alias) class String
export String
String)
Discriminated unions in TypeScript are a way of modeling complex data structures that may take on different forms based on a specific set of conditions or properties. They allow you to define a type that represents multiple related shapes, where each shape is uniquely identified by a shared discriminant property.
In a discriminated union, each variant of the union has a common property, called the discriminant. The discriminant is a literal type, which means it can only have a finite set of possible values. Based on the value of the discriminant property, TypeScript can infer which variant of the union is currently in use.
Here is an example of a discriminated union in TypeScript:
1type type Circle = {
readonly kind: "circle";
readonly radius: number;
}
Circle = {2 readonly (property) kind: "circle"
kind: "circle"3 readonly (property) radius: number
radius: number4}5
6type type Square = {
readonly kind: "square";
readonly sideLength: number;
}
Square = {7 readonly (property) kind: "square"
kind: "square"8 readonly (property) sideLength: number
sideLength: number9}10
11type type Shape = Circle | Square
Shape = type Circle = {
readonly kind: "circle";
readonly radius: number;
}
Circle | type Square = {
readonly kind: "square";
readonly sideLength: number;
}
Square
This code defines a discriminated union using the Schema
module:
1import { import Schema
Schema } from "effect"2
3const const Circle: Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>
Circle = import Schema
Schema.function Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>(fields: {
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}): Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) kind: Schema.Literal<["circle"]>
kind: import Schema
Schema.function Literal<["circle"]>(literals_0: "circle"): Schema.Literal<["circle"]> (+2 overloads)
Literal("circle"),5 (property) radius: typeof Schema.Number
radius: import Schema
Schema.(alias) class Number
export Number
Number6})7
8const const Square: Schema.Struct<{
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}>
Square = import Schema
Schema.function Struct<{
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}>(fields: {
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}): Schema.Struct<{
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({9 (property) kind: Schema.Literal<["square"]>
kind: import Schema
Schema.function Literal<["square"]>(literals_0: "square"): Schema.Literal<["square"]> (+2 overloads)
Literal("square"),10 (property) sideLength: typeof Schema.Number
sideLength: import Schema
Schema.(alias) class Number
export Number
Number11})12
13const const Shape: Schema.Union<[Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>, Schema.Struct<{
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}>]>
Shape = import Schema
Schema.function Union<[Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>, Schema.Struct<{
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}>]>(members_0: Schema.Struct<...>, members_1: Schema.Struct<...>): Schema.Union<...> (+3 overloads)
Union(const Circle: Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>
Circle, const Square: Schema.Struct<{
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}>
Square)
In this example, the Schema.Literal
constructor is used to define the discriminant property (kind
) for each type. The Shape
schema represents a discriminated union of Circle
and Square
.
If you start with a simple union and want to transform it into a discriminated union, you can add a special property to each member. This allows TypeScript to automatically infer the correct type based on the value of the discriminant property.
Example
For example, let’s say you’ve defined a Shape
union as a combination of Circle
and Square
without any special property:
1import { import Schema
Schema } from "effect"2
3const const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle = import Schema
Schema.function Struct<{
radius: typeof Schema.Number;
}>(fields: {
radius: typeof Schema.Number;
}): Schema.Struct<{
radius: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) radius: typeof Schema.Number
radius: import Schema
Schema.(alias) class Number
export Number
Number5})6
7const const Square: Schema.Struct<{
sideLength: typeof Schema.Number;
}>
Square = import Schema
Schema.function Struct<{
sideLength: typeof Schema.Number;
}>(fields: {
sideLength: typeof Schema.Number;
}): Schema.Struct<{
sideLength: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({8 (property) sideLength: typeof Schema.Number
sideLength: import Schema
Schema.(alias) class Number
export Number
Number9})10
11const const Shape: Schema.Union<[Schema.Struct<{
radius: typeof Schema.Number;
}>, Schema.Struct<{
sideLength: typeof Schema.Number;
}>]>
Shape = import Schema
Schema.function Union<[Schema.Struct<{
radius: typeof Schema.Number;
}>, Schema.Struct<{
sideLength: typeof Schema.Number;
}>]>(members_0: Schema.Struct<{
radius: typeof Schema.Number;
}>, members_1: Schema.Struct<...>): Schema.Union<...> (+3 overloads)
Union(const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle, const Square: Schema.Struct<{
sideLength: typeof Schema.Number;
}>
Square)
To make your code more manageable, you may want to transform the simple union into a discriminated union. This way, TypeScript will be able to automatically determine which member of the union you’re working with based on the value of a specific property.
To achieve this, you can add a special property to each member of the union, which will allow TypeScript to know which type it’s dealing with at runtime.
Here’s how you can transform the Shape
schema into another schema that represents a discriminated union:
1import { import Schema
Schema } from "effect"2
3const const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle = import Schema
Schema.function Struct<{
radius: typeof Schema.Number;
}>(fields: {
radius: typeof Schema.Number;
}): Schema.Struct<{
radius: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) radius: typeof Schema.Number
radius: import Schema
Schema.(alias) class Number
export Number
Number5})6
7const const Square: Schema.Struct<{
sideLength: typeof Schema.Number;
}>
Square = import Schema
Schema.function Struct<{
sideLength: typeof Schema.Number;
}>(fields: {
sideLength: typeof Schema.Number;
}): Schema.Struct<{
sideLength: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({8 (property) sideLength: typeof Schema.Number
sideLength: import Schema
Schema.(alias) class Number
export Number
Number9})10
11const const DiscriminatedShape: Schema.Union<[Schema.transform<Schema.Struct<{
radius: typeof Schema.Number;
}>, Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>>, Schema.transform<...>]>
DiscriminatedShape = import Schema
Schema.function Union<[Schema.transform<Schema.Struct<{
radius: typeof Schema.Number;
}>, Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>>, Schema.transform<...>]>(members_0: Schema.transform<...>, members_1: Schema.transform<...>): Schema.Union<...> (+3 overloads)
Union(12 import Schema
Schema.const transform: <Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>, Schema.Struct<{
radius: typeof Schema.Number;
}>>(from: Schema.Struct<{
radius: typeof Schema.Number;
}>, to: Schema.Struct<...>, options: {
...;
} | {
...;
}) => Schema.transform<...> (+1 overload)
Create a new `Schema` by transforming the input and output of an existing `Schema`
using the provided mapping functions.
transform(13 const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle,14 // Add a "kind" property with the literal value "circle" to Circle15 import Schema
Schema.function Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>(fields: {
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}): Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({ ...const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle.(property) TypeLiteral<{ radius: typeof Number$; }, []>.fields: {
readonly radius: typeof Schema.Number;
}
fields, (property) kind: Schema.Literal<["circle"]>
kind: import Schema
Schema.function Literal<["circle"]>(literals_0: "circle"): Schema.Literal<["circle"]> (+2 overloads)
Literal("circle") }),16 {17 (property) strict?: true
strict: true,18 // Add the discriminant property to Circle19 (property) decode: (fromA: {
readonly radius: number;
}, fromI: {
readonly radius: number;
}) => {
readonly radius: number;
readonly kind: "circle";
}
decode: ((parameter) circle: {
readonly radius: number;
}
circle) => ({ ...(parameter) circle: {
readonly radius: number;
}
circle, (property) kind: "circle"
kind: "circle" as type const = "circle"
const }),20 // Remove the discriminant property21 (property) encode: (toI: {
readonly radius: number;
readonly kind: "circle";
}, toA: {
readonly radius: number;
readonly kind: "circle";
}) => {
readonly radius: number;
}
encode: ({ (property) kind: "circle"
kind: (parameter) _kind: "circle"
_kind, ...(parameter) rest: {
radius: number;
}
rest }) => (parameter) rest: {
radius: number;
}
rest22 }23 ),24
25 import Schema
Schema.const transform: <Schema.Struct<{
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}>, Schema.Struct<{
sideLength: typeof Schema.Number;
}>>(from: Schema.Struct<{
sideLength: typeof Schema.Number;
}>, to: Schema.Struct<...>, options: {
...;
} | {
...;
}) => Schema.transform<...> (+1 overload)
Create a new `Schema` by transforming the input and output of an existing `Schema`
using the provided mapping functions.
transform(26 const Square: Schema.Struct<{
sideLength: typeof Schema.Number;
}>
Square,27 // Add a "kind" property with the literal value "square" to Square28 import Schema
Schema.function Struct<{
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}>(fields: {
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}): Schema.Struct<{
kind: Schema.Literal<["square"]>;
sideLength: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({ ...const Square: Schema.Struct<{
sideLength: typeof Schema.Number;
}>
Square.(property) TypeLiteral<{ sideLength: typeof Number$; }, []>.fields: {
readonly sideLength: typeof Schema.Number;
}
fields, (property) kind: Schema.Literal<["square"]>
kind: import Schema
Schema.function Literal<["square"]>(literals_0: "square"): Schema.Literal<["square"]> (+2 overloads)
Literal("square") }),29 {30 (property) strict?: true
strict: true,31 // Add the discriminant property to Square32 (property) decode: (fromA: {
readonly sideLength: number;
}, fromI: {
readonly sideLength: number;
}) => {
readonly sideLength: number;
readonly kind: "square";
}
decode: ((parameter) square: {
readonly sideLength: number;
}
square) => ({ ...(parameter) square: {
readonly sideLength: number;
}
square, (property) kind: "square"
kind: "square" as type const = "square"
const }),33 // Remove the discriminant property34 (property) encode: (toI: {
readonly sideLength: number;
readonly kind: "square";
}, toA: {
readonly sideLength: number;
readonly kind: "square";
}) => {
readonly sideLength: number;
}
encode: ({ (property) kind: "square"
kind: (parameter) _kind: "square"
_kind, ...(parameter) rest: {
sideLength: number;
}
rest }) => (parameter) rest: {
sideLength: number;
}
rest35 }36 )37)38
39namespace 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 radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}, {
readonly radius: number;
} | {
readonly sideLength: number;
}>(schema: Schema.Schema<{
...;
} | {
...;
}, {
...;
} | {
...;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
...;
} | {
...;
}
export decodeUnknownSync
decodeUnknownSync(const DiscriminatedShape: Schema.Union<[Schema.transform<Schema.Struct<{
radius: typeof Schema.Number;
}>, Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>>, Schema.transform<...>]>
DiscriminatedShape)({ (property) radius: number
radius: 10 }))40// Output: { radius: 10, kind: 'circle' }41
42namespace 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(43 import Schema
Schema.(alias) decodeUnknownSync<{
readonly radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}, {
readonly radius: number;
} | {
readonly sideLength: number;
}>(schema: Schema.Schema<{
...;
} | {
...;
}, {
...;
} | {
...;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
...;
} | {
...;
}
export decodeUnknownSync
decodeUnknownSync(const DiscriminatedShape: Schema.Union<[Schema.transform<Schema.Struct<{
radius: typeof Schema.Number;
}>, Schema.Struct<{
kind: Schema.Literal<["circle"]>;
radius: typeof Schema.Number;
}>>, Schema.transform<...>]>
DiscriminatedShape)({ (property) sideLength: number
sideLength: 10 })44)45// Output: { sideLength: 10, kind: 'square' }
The previous solution works perfectly and shows how we can add properties to our schema at will, making it easier to consume the result within our domain model.
However, it requires a lot of boilerplate. Fortunately, there is an API called Schema.attachPropertySignature
designed specifically for this use case, which allows us to achieve the same result with much less effort:
1import { import Schema
Schema } from "effect"2
3const const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle = import Schema
Schema.function Struct<{
radius: typeof Schema.Number;
}>(fields: {
radius: typeof Schema.Number;
}): Schema.Struct<{
radius: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) radius: typeof Schema.Number
radius: import Schema
Schema.(alias) class Number
export Number
Number5})6
7const const Square: Schema.Struct<{
sideLength: typeof Schema.Number;
}>
Square = import Schema
Schema.function Struct<{
sideLength: typeof Schema.Number;
}>(fields: {
sideLength: typeof Schema.Number;
}): Schema.Struct<{
sideLength: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({8 (property) sideLength: typeof Schema.Number
sideLength: import Schema
Schema.(alias) class Number
export Number
Number9})10
11const const DiscriminatedShape: Schema.Union<[Schema.SchemaClass<{
readonly radius: number;
readonly kind: "circle";
}, {
readonly radius: number;
}, never>, Schema.SchemaClass<{
readonly sideLength: number;
readonly kind: "square";
}, {
...;
}, never>]>
DiscriminatedShape = import Schema
Schema.function Union<[Schema.SchemaClass<{
readonly radius: number;
readonly kind: "circle";
}, {
readonly radius: number;
}, never>, Schema.SchemaClass<{
readonly sideLength: number;
readonly kind: "square";
}, {
...;
}, never>]>(members_0: Schema.SchemaClass<...>, members_1: Schema.SchemaClass<...>): Schema.Union<...> (+3 overloads)
Union(12 const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle.(method) Pipeable.pipe<Schema.Struct<{
radius: typeof Schema.Number;
}>, Schema.SchemaClass<{
readonly radius: number;
readonly kind: "circle";
}, {
readonly radius: number;
}, never>>(this: Schema.Struct<...>, ab: (_: Schema.Struct<...>) => Schema.SchemaClass<...>): Schema.SchemaClass<...> (+21 overloads)
pipe(import Schema
Schema.const attachPropertySignature: <"kind", "circle", {
readonly radius: number;
}>(key: "kind", value: "circle", annotations?: Schema.Annotations.Schema<{
readonly radius: number;
readonly kind: "circle";
}, readonly []> | undefined) => <I, R>(schema: Schema.SchemaClass<...>) => Schema.SchemaClass<...> (+1 overload)
Attaches a property signature with the specified key and value to the schema.
This API is useful when you want to add a property to your schema which doesn't describe the shape of the input,
but rather maps to another schema, for example when you want to add a discriminant to a simple union.
attachPropertySignature("kind", "circle")),13 const Square: Schema.Struct<{
sideLength: typeof Schema.Number;
}>
Square.(method) Pipeable.pipe<Schema.Struct<{
sideLength: typeof Schema.Number;
}>, Schema.SchemaClass<{
readonly sideLength: number;
readonly kind: "square";
}, {
readonly sideLength: number;
}, never>>(this: Schema.Struct<...>, ab: (_: Schema.Struct<...>) => Schema.SchemaClass<...>): Schema.SchemaClass<...> (+21 overloads)
pipe(import Schema
Schema.const attachPropertySignature: <"kind", "square", {
readonly sideLength: number;
}>(key: "kind", value: "square", annotations?: Schema.Annotations.Schema<{
readonly sideLength: number;
readonly kind: "square";
}, readonly []> | undefined) => <I, R>(schema: Schema.SchemaClass<...>) => Schema.SchemaClass<...> (+1 overload)
Attaches a property signature with the specified key and value to the schema.
This API is useful when you want to add a property to your schema which doesn't describe the shape of the input,
but rather maps to another schema, for example when you want to add a discriminant to a simple union.
attachPropertySignature("kind", "square"))14)15
16// decoding17namespace 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 radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}, {
readonly radius: number;
} | {
readonly sideLength: number;
}>(schema: Schema.Schema<{
...;
} | {
...;
}, {
...;
} | {
...;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
...;
} | {
...;
}
export decodeUnknownSync
decodeUnknownSync(const DiscriminatedShape: Schema.Union<[Schema.SchemaClass<{
readonly radius: number;
readonly kind: "circle";
}, {
readonly radius: number;
}, never>, Schema.SchemaClass<{
readonly sideLength: number;
readonly kind: "square";
}, {
...;
}, never>]>
DiscriminatedShape)({ (property) radius: number
radius: 10 }))18// Output: { radius: 10, kind: 'circle' }19
20// encoding21namespace 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(22 import Schema
Schema.(alias) encodeSync<{
readonly radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}, {
readonly radius: number;
} | {
readonly sideLength: number;
}>(schema: Schema.Schema<{
...;
} | {
...;
}, {
...;
} | {
...;
}, never>, options?: ParseOptions): (a: {
...;
} | {
...;
}, overrideOptions?: ParseOptions) => {
...;
} | {
...;
}
export encodeSync
encodeSync(const DiscriminatedShape: Schema.Union<[Schema.SchemaClass<{
readonly radius: number;
readonly kind: "circle";
}, {
readonly radius: number;
}, never>, Schema.SchemaClass<{
readonly sideLength: number;
readonly kind: "square";
}, {
...;
}, never>]>
DiscriminatedShape)({23 (property) kind: "circle"
kind: "circle",24 (property) radius: number
radius: 1025 })26)27// Output: { radius: 10 }
You can access the individual members of a union schema represented as a tuple:
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Union<[typeof Schema.String, typeof Schema.Number]>
schema = import Schema
Schema.function Union<[typeof Schema.String, typeof Schema.Number]>(members_0: typeof Schema.String, members_1: typeof Schema.Number): Schema.Union<[typeof Schema.String, typeof Schema.Number]> (+3 overloads)
Union(import Schema
Schema.(alias) class String
export String
String, import Schema
Schema.(alias) class Number
export Number
Number)4
5// Accesses the members of the union6const const members: readonly [typeof Schema.String, typeof Schema.Number]
members = const schema: Schema.Union<[typeof Schema.String, typeof Schema.Number]>
schema.(property) Union<[typeof String$, typeof Number$]>.members: readonly [typeof Schema.String, typeof Schema.Number]
members7
8const const firstMember: typeof Schema.String
firstMember = const members: readonly [typeof Schema.String, typeof Schema.Number]
members[0]9// ^? const firstMember: typeof Schema.String1011const secondMember = members[1]12// ^? const secondMember: typeof Schema.Number
The Schema
module allows you to define tuples, which are ordered collections of elements that may have different types.
You can define tuples with required, optional, or rest elements.
To define a tuple with required elements, you can use the Schema.Tuple
constructor and simply list the element schemas in order:
Example
1import { import Schema
Schema } from "effect"2
3// Define a tuple with a string and a number as required elements4const const schema: Schema.Tuple<[typeof Schema.String, typeof Schema.Number]>
schema = import Schema
Schema.function Tuple<[typeof Schema.String, typeof Schema.Number]>(elements_0: typeof Schema.String, elements_1: typeof Schema.Number): Schema.Tuple<[typeof Schema.String, typeof Schema.Number]> (+1 overload)
Tuple(import Schema
Schema.(alias) class String
export String
String, import Schema
Schema.(alias) class Number
export Number
Number)5
6// readonly [string, number]7type type Type = readonly [string, number]
Type = typeof const schema: Schema.Tuple<[typeof Schema.String, typeof Schema.Number]>
schema.(property) Schema<readonly [string, number], readonly [string, number], never>.Type: readonly [string, number]
Type
You can append additional required elements to an existing tuple by using the spread operator:
Example
1import { import Schema
Schema } from "effect"2
3const const tuple1: Schema.Tuple<[typeof Schema.String, typeof Schema.Number]>
tuple1 = import Schema
Schema.function Tuple<[typeof Schema.String, typeof Schema.Number]>(elements_0: typeof Schema.String, elements_1: typeof Schema.Number): Schema.Tuple<[typeof Schema.String, typeof Schema.Number]> (+1 overload)
Tuple(import Schema
Schema.(alias) class String
export String
String, import Schema
Schema.(alias) class Number
export Number
Number)4
5// Append a boolean to the existing tuple6const const tuple2: Schema.Tuple<[typeof Schema.String, typeof Schema.Number, typeof Schema.Boolean]>
tuple2 = import Schema
Schema.function Tuple<[typeof Schema.String, typeof Schema.Number, typeof Schema.Boolean]>(elements_0: typeof Schema.String, elements_1: typeof Schema.Number, elements_2: typeof Schema.Boolean): Schema.Tuple<...> (+1 overload)
Tuple(...const tuple1: Schema.Tuple<[typeof Schema.String, typeof Schema.Number]>
tuple1.(property) TupleType<[typeof String$, typeof Number$], []>.elements: readonly [typeof Schema.String, typeof Schema.Number]
elements, import Schema
Schema.(alias) class Boolean
export Boolean
Boolean)7
8// readonly [string, number, boolean]9type type Type = readonly [string, number, boolean]
Type = typeof const tuple2: Schema.Tuple<[typeof Schema.String, typeof Schema.Number, typeof Schema.Boolean]>
tuple2.(property) Schema<readonly [string, number, boolean], readonly [string, number, boolean], never>.Type: readonly [string, number, boolean]
Type
To define an optional element, use the Schema.optionalElement
constructor.
Example
1import { import Schema
Schema } from "effect"2
3// Define a tuple with a required string and an optional number4const const schema: Schema.Tuple<[typeof Schema.String, Schema.Element<typeof Schema.Number, "?">]>
schema = import Schema
Schema.function Tuple<[typeof Schema.String, Schema.Element<typeof Schema.Number, "?">]>(elements_0: typeof Schema.String, elements_1: Schema.Element<typeof Schema.Number, "?">): Schema.Tuple<...> (+1 overload)
Tuple(5 import Schema
Schema.(alias) class String
export String
String, // required element6 import Schema
Schema.const optionalElement: <typeof Schema.Number>(self: typeof Schema.Number) => Schema.Element<typeof Schema.Number, "?">
optionalElement(import Schema
Schema.(alias) class Number
export Number
Number) // optional element7)8
9// readonly [string, number?]10type type Type = readonly [string, number?]
Type = typeof const schema: Schema.Tuple<[typeof Schema.String, Schema.Element<typeof Schema.Number, "?">]>
schema.(property) Schema<readonly [string, number?], readonly [string, number?], never>.Type: readonly [string, number?]
Type
To define a rest element, add it after the list of required or optional elements. The rest element allows the tuple to accept additional elements of a specific type.
Example
1import { import Schema
Schema } from "effect"2
3// Define a tuple with required elements and a rest element of type boolean4const const schema: Schema.TupleType<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean]>
schema = import Schema
Schema.function Tuple<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean]>(elements: readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], rest_0: typeof Schema.Boolean): Schema.TupleType<...> (+1 overload)
Tuple(5 [import Schema
Schema.(alias) class String
export String
String, import Schema
Schema.const optionalElement: <typeof Schema.Number>(self: typeof Schema.Number) => Schema.Element<typeof Schema.Number, "?">
optionalElement(import Schema
Schema.(alias) class Number
export Number
Number)], // elements6 import Schema
Schema.(alias) class Boolean
export Boolean
Boolean // rest element7)8
9// readonly [string, number?, ...boolean[]]10type type Type = readonly [string, number?, ...boolean[]]
Type = typeof const schema: Schema.TupleType<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean]>
schema.(property) Schema<readonly [string, number?, ...boolean[]], readonly [string, number?, ...boolean[]], never>.Type: readonly [string, number?, ...boolean[]]
Type
You can also include other elements after the rest:
1import { import Schema
Schema } from "effect"2
3// Define a tuple with required elements, a rest element,4// and an additional element5const const schema: Schema.TupleType<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean, typeof Schema.String]>
schema = import Schema
Schema.function Tuple<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean, typeof Schema.String]>(elements: readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], rest_0: typeof Schema.Boolean, rest_1: typeof Schema.String): Schema.TupleType<...> (+1 overload)
Tuple(6 [import Schema
Schema.(alias) class String
export String
String, import Schema
Schema.const optionalElement: <typeof Schema.Number>(self: typeof Schema.Number) => Schema.Element<typeof Schema.Number, "?">
optionalElement(import Schema
Schema.(alias) class Number
export Number
Number)], // elements7 import Schema
Schema.(alias) class Boolean
export Boolean
Boolean, // rest element8 import Schema
Schema.(alias) class String
export String
String // additional element9)10
11// readonly [string, number | undefined, ...boolean[], string]12type type Type = readonly [string, number | undefined, ...boolean[], string]
Type = typeof const schema: Schema.TupleType<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean, typeof Schema.String]>
schema.(property) Schema<readonly [string, number | undefined, ...boolean[], string], readonly [string, number | undefined, ...boolean[], string], never>.Type: readonly [string, number | undefined, ...boolean[], string]
Type
Annotations are useful for adding metadata to tuple elements, making it easier to describe their purpose or requirements. This is especially helpful for generating documentation or JSON schemas.
Example
1import { import JSONSchema
JSONSchema, import Schema
Schema } from "effect"2
3// Define a tuple representing a point with annotations for each coordinate4const const Point: Schema.Tuple<[Schema.Element<typeof Schema.Number, "">, Schema.Element<typeof Schema.Number, "?">]>
Point = import Schema
Schema.function Tuple<[Schema.Element<typeof Schema.Number, "">, Schema.Element<typeof Schema.Number, "?">]>(elements_0: Schema.Element<typeof Schema.Number, "">, elements_1: Schema.Element<...>): Schema.Tuple<...> (+1 overload)
Tuple(5 import Schema
Schema.const element: <typeof Schema.Number>(self: typeof Schema.Number) => Schema.Element<typeof Schema.Number, "">
element(import Schema
Schema.(alias) class Number
export Number
Number).(method) Element<typeof Number$, "">.annotations(annotations: Schema.Element<S extends Schema.Schema<in out A, in out I = A, out R = never>.Any, Token extends Schema.Element.Token>.Annotations<number>): Schema.Element<typeof Schema.Number, "">
annotations({6 (property) Annotations.Doc<number>.title?: string
title: "X",7 (property) Annotations.Doc<number>.description?: string
description: "X coordinate"8 }),9 import Schema
Schema.const optionalElement: <typeof Schema.Number>(self: typeof Schema.Number) => Schema.Element<typeof Schema.Number, "?">
optionalElement(import Schema
Schema.(alias) class Number
export Number
Number).(method) Element<typeof Number$, "?">.annotations(annotations: Schema.Element<S extends Schema.Schema<in out A, in out I = A, out R = never>.Any, Token extends Schema.Element.Token>.Annotations<number>): Schema.Element<typeof Schema.Number, "?">
annotations({10 (property) Annotations.Doc<number>.title?: string
title: "Y",11 (property) Annotations.Doc<number>.description?: string
description: "optional Y coordinate"12 })13)14
15// Generate a JSON Schema from the tuple16namespace 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 JSONSchema
JSONSchema.const make: <readonly [number, number?], readonly [number, number?], never>(schema: Schema.Schema<readonly [number, number?], readonly [number, number?], never>) => JSONSchema.JsonSchema7Root
make(const Point: Schema.Tuple<[Schema.Element<typeof Schema.Number, "">, Schema.Element<typeof Schema.Number, "?">]>
Point))17/*18Output:19{20 '$schema': 'http://json-schema.org/draft-07/schema#',21 type: 'array',22 minItems: 1,23 items: [24 { type: 'number', description: 'X coordinate', title: 'X' },25 {26 type: 'number',27 description: 'optional Y coordinate',28 title: 'Y'29 }30 ],31 additionalItems: false32}33*/
You can access the elements and rest elements of a tuple schema using the elements
and rest
properties:
1import { import Schema
Schema } from "effect"2
3// Define a tuple with required, optional, and rest elements4const const schema: Schema.TupleType<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean, typeof Schema.String]>
schema = import Schema
Schema.function Tuple<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean, typeof Schema.String]>(elements: readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], rest_0: typeof Schema.Boolean, rest_1: typeof Schema.String): Schema.TupleType<...> (+1 overload)
Tuple(5 [import Schema
Schema.(alias) class String
export String
String, import Schema
Schema.const optionalElement: <typeof Schema.Number>(self: typeof Schema.Number) => Schema.Element<typeof Schema.Number, "?">
optionalElement(import Schema
Schema.(alias) class Number
export Number
Number)], // elements6 import Schema
Schema.(alias) class Boolean
export Boolean
Boolean, // rest element7 import Schema
Schema.(alias) class String
export String
String // additional element8)9
10// Access the required and optional elements of the tuple11const const tupleElements: readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">]
tupleElements = const schema: Schema.TupleType<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean, typeof Schema.String]>
schema.(property) TupleType<readonly [typeof String$, Element<typeof Number$, "?">], [typeof Boolean$, typeof String$]>.elements: readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">]
elements12// ^? const tupleElements: readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">]13
14// Accconst restElement: readonly [typeof Schema.Boolean, typeof Schema.String]
ess the rest econst schema: Schema.TupleType<readonly [typeof Schema.String, Schema.Element<typeof Schema.Number, "?">], [typeof Schema.Boolean, typeof Schema.String]>
lement (property) TupleType<readonly [typeof String$, Element<typeof Number$, "?">], [typeof Boolean$, typeof String$]>.rest: readonly [typeof Schema.Boolean, typeof Schema.String]
of the tuple15const restElement = schema.rest16// ^? const restElement: readonly [typeof Schema.Boolean, typeof Schema.String]
The Schema
module allows you to define schemas for arrays, making it easy to validate collections of elements of a specific type.
Example
1import { import Schema
Schema } from "effect"2
3// Define a schema for an array of numbers4const const schema: Schema.Array$<typeof Schema.Number>
schema = import Schema
Schema.(alias) Array<typeof Schema.Number>(value: typeof Schema.Number): Schema.Array$<typeof Schema.Number>
export Array
Array(import Schema
Schema.(alias) class Number
export Number
Number)5
6// readonly number[]7type type Type = readonly number[]
Type = typeof const schema: Schema.Array$<typeof Schema.Number>
schema.(property) Schema<readonly number[], readonly number[], never>.Type: readonly number[]
Type
By default, Schema.Array
generates a type marked as readonly
.
To create a schema for a mutable array, you can use the Schema.mutable
function, which makes the array type mutable in a shallow manner.
Example
1import { import Schema
Schema } from "effect"2
3// Define a schema for a mutable array of numbers4const const schema: Schema.mutable<Schema.Array$<typeof Schema.Number>>
schema = import Schema
Schema.const mutable: <Schema.Array$<typeof Schema.Number>>(schema: Schema.Array$<typeof Schema.Number>) => Schema.mutable<Schema.Array$<typeof Schema.Number>>
Creates a new schema with shallow mutability applied to its properties.
mutable(import Schema
Schema.(alias) Array<typeof Schema.Number>(value: typeof Schema.Number): Schema.Array$<typeof Schema.Number>
export Array
Array(import Schema
Schema.(alias) class Number
export Number
Number))5
6// number[]7type type Type = number[]
Type = typeof const schema: Schema.mutable<Schema.Array$<typeof Schema.Number>>
schema.(property) Schema<number[], number[], never>.Type: number[]
Type
You can access the value type of an array schema using the value
property:
1import { import Schema
Schema } from "effect"2
3// Define a schema for an array of numbers4const const schema: Schema.Array$<typeof Schema.Number>
schema = import Schema
Schema.(alias) Array<typeof Schema.Number>(value: typeof Schema.Number): Schema.Array$<typeof Schema.Number>
export Array
Array(import Schema
Schema.(alias) class Number
export Number
Number)5
6// Access the value type of the array schema7const const value: typeof Schema.Number
value = const schema: Schema.Array$<typeof Schema.Number>
schema.(property) Array$<typeof Number$>.value: typeof Schema.Number
value8// ^? const value: typeof Schema.Number
The Schema
module also provides a way to define schemas for non-empty arrays, ensuring that the array always contains at least one element.
Example
1import { import Schema
Schema } from "effect"2
3// Define a schema for a non-empty array of numbers4const const schema: Schema.NonEmptyArray<typeof Schema.Number>
schema = import Schema
Schema.const NonEmptyArray: <typeof Schema.Number>(value: typeof Schema.Number) => Schema.NonEmptyArray<typeof Schema.Number>
NonEmptyArray(import Schema
Schema.(alias) class Number
export Number
Number)5
6// readonly [number, ...number[]]7type type Type = readonly [number, ...number[]]
Type = typeof const schema: Schema.NonEmptyArray<typeof Schema.Number>
schema.(property) Schema<readonly [number, ...number[]], readonly [number, ...number[]], never>.Type: readonly [number, ...number[]]
Type
You can access the value type of a non-empty array schema using the value
property:
1import { import Schema
Schema } from "effect"2
3// Define a schema for a non-empty array of numbers4const const schema: Schema.NonEmptyArray<typeof Schema.Number>
schema = import Schema
Schema.const NonEmptyArray: <typeof Schema.Number>(value: typeof Schema.Number) => Schema.NonEmptyArray<typeof Schema.Number>
NonEmptyArray(import Schema
Schema.(alias) class Number
export Number
Number)5
6// Access the value type of the non-empty array schema7const const value: typeof Schema.Number
value = const schema: Schema.NonEmptyArray<typeof Schema.Number>
schema.(property) NonEmptyArray<typeof Number$>.value: typeof Schema.Number
value8// ^? const value: typeof Schema.Number
The Schema
module provides support for defining record types, which are collections of key-value pairs where the key can be a string, symbol, or other types, and the value has a defined schema.
1import { import Schema
Schema } from "effect"2
3// Define a record schema with string keys and number values4const const schema: Schema.Record$<typeof Schema.String, typeof Schema.Number>
schema = import Schema
Schema.const Record: <typeof Schema.String, typeof Schema.Number>(options: {
readonly key: typeof Schema.String;
readonly value: typeof Schema.Number;
}) => Schema.Record$<typeof Schema.String, typeof Schema.Number>
Record({ (property) key: typeof Schema.String
key: import Schema
Schema.(alias) class String
export String
String, (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number })5
6// { readonly [x: string]: number; }7type type Type = {
readonly [x: string]: number;
}
Type = typeof const schema: Schema.Record$<typeof Schema.String, typeof Schema.Number>
schema.(property) Schema<{ readonly [x: string]: number; }, { readonly [x: string]: number; }, never>.Type: {
readonly [x: string]: number;
}
Type
1import { import Schema
Schema } from "effect"2
3// Define a record schema with symbol keys and number values4const const schema: Schema.Record$<typeof Schema.SymbolFromSelf, typeof Schema.Number>
schema = import Schema
Schema.const Record: <typeof Schema.SymbolFromSelf, typeof Schema.Number>(options: {
readonly key: typeof Schema.SymbolFromSelf;
readonly value: typeof Schema.Number;
}) => Schema.Record$<typeof Schema.SymbolFromSelf, typeof Schema.Number>
Record({5 (property) key: typeof Schema.SymbolFromSelf
key: import Schema
Schema.class SymbolFromSelf
SymbolFromSelf,6 (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number7})8
9// { readonly [x: symbol]: number; }10type type Type = {
readonly [x: symbol]: number;
}
Type = typeof const schema: Schema.Record$<typeof Schema.SymbolFromSelf, typeof Schema.Number>
schema.(property) Schema<{ readonly [x: symbol]: number; }, { readonly [x: symbol]: number; }, never>.Type: {
readonly [x: symbol]: number;
}
Type
1import { import Schema
Schema } from "effect"2
3// Define a record schema where keys are limited4// to specific string literals ("a" or "b")5const const schema: Schema.Record$<Schema.Union<[Schema.Literal<["a"]>, Schema.Literal<["b"]>]>, typeof Schema.Number>
schema = import Schema
Schema.const Record: <Schema.Union<[Schema.Literal<["a"]>, Schema.Literal<["b"]>]>, typeof Schema.Number>(options: {
readonly key: Schema.Union<[Schema.Literal<["a"]>, Schema.Literal<["b"]>]>;
readonly value: typeof Schema.Number;
}) => Schema.Record$<...>
Record({6 (property) key: Schema.Union<[Schema.Literal<["a"]>, Schema.Literal<["b"]>]>
key: import Schema
Schema.function Union<[Schema.Literal<["a"]>, Schema.Literal<["b"]>]>(members_0: Schema.Literal<["a"]>, members_1: Schema.Literal<["b"]>): Schema.Union<[Schema.Literal<["a"]>, Schema.Literal<...>]> (+3 overloads)
Union(import Schema
Schema.function Literal<["a"]>(literals_0: "a"): Schema.Literal<["a"]> (+2 overloads)
Literal("a"), import Schema
Schema.function Literal<["b"]>(literals_0: "b"): Schema.Literal<["b"]> (+2 overloads)
Literal("b")),7 (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number8})9
10// { readonly a: number; readonly b: number; }11type type Type = {
readonly a: number;
readonly b: number;
}
Type = typeof const schema: Schema.Record$<Schema.Union<[Schema.Literal<["a"]>, Schema.Literal<["b"]>]>, typeof Schema.Number>
schema.(property) Schema<{ readonly a: number; readonly b: number; }, { readonly a: number; readonly b: number; }, never>.Type: {
readonly a: number;
readonly b: number;
}
Type
1import { import Schema
Schema } from "effect"2
3// Define a record schema with keys that match4// the template literal pattern "a${string}"5const const schema: Schema.Record$<Schema.TemplateLiteral<`a${string}`>, typeof Schema.Number>
schema = import Schema
Schema.const Record: <Schema.TemplateLiteral<`a${string}`>, typeof Schema.Number>(options: {
readonly key: Schema.TemplateLiteral<`a${string}`>;
readonly value: typeof Schema.Number;
}) => Schema.Record$<...>
Record({6 (property) key: Schema.TemplateLiteral<`a${string}`>
key: import Schema
Schema.const TemplateLiteral: <[Schema.Literal<["a"]>, typeof Schema.String]>(head: Schema.Literal<["a"]>, tail_0: typeof Schema.String) => Schema.TemplateLiteral<`a${string}`>
TemplateLiteral(import Schema
Schema.function Literal<["a"]>(literals_0: "a"): Schema.Literal<["a"]> (+2 overloads)
Literal("a"), import Schema
Schema.(alias) class String
export String
String),7 (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number8})9
10// { readonly [x: `a${string}`]: number; }11type type Type = {
readonly [x: `a${string}`]: number;
}
Type = typeof const schema: Schema.Record$<Schema.TemplateLiteral<`a${string}`>, typeof Schema.Number>
schema.(property) Schema<{ readonly [x: `a${string}`]: number; }, { readonly [x: `a${string}`]: number; }, never>.Type: {
readonly [x: `a${string}`]: number;
}
Type
1import { import Schema
Schema } from "effect"2
3// Define a record schema where keys are strings with a minimum length of 24const const schema: Schema.Record$<Schema.filter<Schema.Schema<string, string, never>>, typeof Schema.Number>
schema = import Schema
Schema.const Record: <Schema.filter<Schema.Schema<string, string, never>>, typeof Schema.Number>(options: {
readonly key: Schema.filter<Schema.Schema<string, string, never>>;
readonly value: typeof Schema.Number;
}) => Schema.Record$<...>
Record({5 (property) key: Schema.filter<Schema.Schema<string, string, never>>
key: import Schema
Schema.(alias) class String
export String
String.(method) Pipeable.pipe<typeof Schema.String, Schema.filter<Schema.Schema<string, string, never>>>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.filter<Schema.Schema<string, string, never>>): Schema.filter<...> (+21 overloads)
pipe(import Schema
Schema.const minLength: <string>(minLength: number, annotations?: Schema.Annotations.Filter<string, string> | undefined) => <I, R>(self: Schema.Schema<string, I, R>) => Schema.filter<...>
minLength(2)),6 (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number7})8
9// { readonly [x: string]: number; }10type type Type = {
readonly [x: string]: number;
}
Type = typeof const schema: Schema.Record$<Schema.filter<Schema.Schema<string, string, never>>, typeof Schema.Number>
schema.(property) Schema<{ readonly [x: string]: number; }, { readonly [x: string]: number; }, never>.Type: {
readonly [x: string]: number;
}
Type
By default, Schema.Record
generates a type marked as readonly
.
To create a schema for a mutable record, you can use the Schema.mutable
function, which makes the record type mutable in a shallow manner.
1import { import Schema
Schema } from "effect"2
3// Create a schema for a mutable record with string keys and number values4const const schema: Schema.mutable<Schema.Record$<typeof Schema.String, typeof Schema.Number>>
schema = import Schema
Schema.const mutable: <Schema.Record$<typeof Schema.String, typeof Schema.Number>>(schema: Schema.Record$<typeof Schema.String, typeof Schema.Number>) => Schema.mutable<Schema.Record$<typeof Schema.String, typeof Schema.Number>>
Creates a new schema with shallow mutability applied to its properties.
mutable(5 import Schema
Schema.const Record: <typeof Schema.String, typeof Schema.Number>(options: {
readonly key: typeof Schema.String;
readonly value: typeof Schema.Number;
}) => Schema.Record$<typeof Schema.String, typeof Schema.Number>
Record({ (property) key: typeof Schema.String
key: import Schema
Schema.(alias) class String
export String
String, (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number })6)7
8// { [x: string]: number; }9type type Type = {
[x: string]: number;
}
Type = typeof const schema: Schema.mutable<Schema.Record$<typeof Schema.String, typeof Schema.Number>>
schema.(property) Schema<{ [x: string]: number; }, { [x: string]: number; }, never>.Type: {
[x: string]: number;
}
Type
You can access the key
and value
types of a record schema using the key
and value
properties:
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Record$<typeof Schema.String, typeof Schema.Number>
schema = import Schema
Schema.const Record: <typeof Schema.String, typeof Schema.Number>(options: {
readonly key: typeof Schema.String;
readonly value: typeof Schema.Number;
}) => Schema.Record$<typeof Schema.String, typeof Schema.Number>
Record({ (property) key: typeof Schema.String
key: import Schema
Schema.(alias) class String
export String
String, (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number })4
5// Accesses the key6const const key: typeof Schema.String
key = const schema: Schema.Record$<typeof Schema.String, typeof Schema.Number>
schema.(property) Record$<typeof String$, typeof Number$>.key: typeof Schema.String
key7// ^? const value: typeof Schema.String8
9// Accconst value: typeof Schema.Number
esses thconst schema: Schema.Record$<typeof Schema.String, typeof Schema.Number>
e value(property) Record$<typeof String$, typeof Number$>.value: typeof Schema.Number
10const value = schema.value11// ^? const value: typeof Schema.Number
The Schema.Struct
constructor allows you to define a schema for an object with specific properties.
Example
1import { import Schema
Schema } from "effect"2
3// Define a struct schema for an object with properties "name" (string) and "age" (number)4const const schema: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
schema = 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// { readonly name: string; readonly age: number; }10type type Type = {
readonly name: string;
readonly age: number;
}
Type = typeof const schema: Schema.Struct<{
name: typeof Schema.String;
age: typeof Schema.Number;
}>
schema.(property) Schema<{ readonly name: string; readonly age: number; }, { readonly name: string; readonly age: number; }, never>.Type: {
readonly name: string;
readonly age: number;
}
Type
The Schema.Struct
constructor can optionally accept a list of key/value pairs representing index signatures, allowing you to define additional dynamic properties.
declare const Struct: (props, ...indexSignatures) => Struct<...>
Example
1import { import Schema
Schema } from "effect"2
3// Define a struct with a specific property "a"4// and an index signature for other properties5const const schema: Schema.TypeLiteral<{
a: typeof Schema.Number;
}, readonly [{
readonly key: typeof Schema.String;
readonly value: typeof Schema.Number;
}]>
schema = import Schema
Schema.function Struct<{
a: typeof Schema.Number;
}, readonly [{
readonly key: typeof Schema.String;
readonly value: typeof Schema.Number;
}]>(fields: {
a: typeof Schema.Number;
}, records_0: {
readonly key: typeof Schema.String;
readonly value: typeof Schema.Number;
}): Schema.TypeLiteral<...> (+1 overload)
namespace Struct
Struct(6 {7 (property) a: typeof Schema.Number
a: import Schema
Schema.(alias) class Number
export Number
Number8 },9 { (property) key: typeof Schema.String
key: import Schema
Schema.(alias) class String
export String
String, (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number }10)11
12// { readonly [x: string]: number; readonly a: number; }13type type Type = {
readonly [x: string]: number;
readonly a: number;
}
Type = typeof const schema: Schema.TypeLiteral<{
a: typeof Schema.Number;
}, readonly [{
readonly key: typeof Schema.String;
readonly value: typeof Schema.Number;
}]>
schema.(property) Schema<{ readonly [x: string]: number; readonly a: number; }, { readonly [x: string]: number; readonly a: number; }, never>.Type: {
readonly [x: string]: number;
readonly a: number;
}
Type
Since the Schema.Record
constructor returns a schema that exposes both the key
and value
, you can simplify the above code by using the Schema.Record
constructor:
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.TypeLiteral<{
a: typeof Schema.Number;
}, readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]>
schema = import Schema
Schema.function Struct<{
a: typeof Schema.Number;
}, readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]>(fields: {
a: typeof Schema.Number;
}, records_0: Schema.Record$<typeof Schema.String, typeof Schema.Number>): Schema.TypeLiteral<...> (+1 overload)
namespace Struct
Struct(4 { (property) a: typeof Schema.Number
a: import Schema
Schema.(alias) class Number
export Number
Number },5 import Schema
Schema.const Record: <typeof Schema.String, typeof Schema.Number>(options: {
readonly key: typeof Schema.String;
readonly value: typeof Schema.Number;
}) => Schema.Record$<typeof Schema.String, typeof Schema.Number>
Record({ (property) key: typeof Schema.String
key: import Schema
Schema.(alias) class String
export String
String, (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number })6)7
8// { readonly [x: string]: number; readonly a: number; }9type type Type = {
readonly [x: string]: number;
readonly a: number;
}
Type = typeof const schema: Schema.TypeLiteral<{
a: typeof Schema.Number;
}, readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]>
schema.(property) Schema<{ readonly [x: string]: number; readonly a: number; }, { readonly [x: string]: number; readonly a: number; }, never>.Type: {
readonly [x: string]: number;
readonly a: number;
}
Type
By default, Schema.Struct
generates a type with properties marked as readonly
.
To create a mutable version of the struct, use the Schema.mutable
function, which makes the properties mutable in a shallow manner.
Example
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.mutable<Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>>
schema = import Schema
Schema.const mutable: <Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>>(schema: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>) => Schema.mutable<Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>>
Creates a new schema with shallow mutability applied to its properties.
mutable(4 import Schema
Schema.function Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>(fields: {
a: typeof Schema.String;
b: typeof Schema.Number;
}): Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({ (property) a: typeof Schema.String
a: import Schema
Schema.(alias) class String
export String
String, (property) b: typeof Schema.Number
b: import Schema
Schema.(alias) class Number
export Number
Number })5)6
7// { a: string; b: number; }8type type Type = {
a: string;
b: number;
}
Type = typeof const schema: Schema.mutable<Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>>
schema.(property) Schema<{ a: string; b: number; }, { a: string; b: number; }, never>.Type: {
a: string;
b: number;
}
Type
You can access the fields and records of a struct schema using the fields
and records
properties:
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.TypeLiteral<{
a: typeof Schema.Number;
}, readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]>
schema = import Schema
Schema.function Struct<{
a: typeof Schema.Number;
}, readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]>(fields: {
a: typeof Schema.Number;
}, records_0: Schema.Record$<typeof Schema.String, typeof Schema.Number>): Schema.TypeLiteral<...> (+1 overload)
namespace Struct
Struct(4 { (property) a: typeof Schema.Number
a: import Schema
Schema.(alias) class Number
export Number
Number },5 import Schema
Schema.const Record: <typeof Schema.String, typeof Schema.Number>(options: {
readonly key: typeof Schema.String;
readonly value: typeof Schema.Number;
}) => Schema.Record$<typeof Schema.String, typeof Schema.Number>
Record({ (property) key: typeof Schema.String
key: import Schema
Schema.(alias) class String
export String
String, (property) value: typeof Schema.Number
value: import Schema
Schema.(alias) class Number
export Number
Number })6)7
8// Accesses the fields9const const fields: {
readonly a: typeof Schema.Number;
}
fields = const schema: Schema.TypeLiteral<{
a: typeof Schema.Number;
}, readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]>
schema.(property) TypeLiteral<{ a: typeof Number$; }, readonly [Record$<typeof String$, typeof Number$>]>.fields: {
readonly a: typeof Schema.Number;
}
fields10// ^? const fields: { readonly a: typeof Schema.Number; }11
12// Accconst records: readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]
esses the const schema: Schema.TypeLiteral<{
a: typeof Schema.Number;
}, readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]>
records(property) TypeLiteral<{ a: typeof Number$; }, readonly [Record$<typeof String$, typeof Number$>]>.records: readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]
13const records = schema.records14// ^? const records: readonly [Schema.Record$<typeof Schema.String, typeof Schema.Number>]
In TypeScript tags help to enhance type discrimination and pattern matching by providing a simple yet powerful way to define and recognize different data types.
A tag is a literal value added to data structures, commonly used in structs, to distinguish between various object types or variants within tagged unions. This literal acts as a discriminator, making it easier to handle and process different types of data correctly and efficiently.
The Schema.tag
constructor is specifically designed to create a property signature that holds a specific literal value, serving as the discriminator for object types.
Example
1import { import Schema
Schema } from "effect"2
3const const User: Schema.Struct<{
_tag: Schema.tag<"User">;
name: typeof Schema.String;
age: typeof Schema.Number;
}>
User = import Schema
Schema.function Struct<{
_tag: Schema.tag<"User">;
name: typeof Schema.String;
age: typeof Schema.Number;
}>(fields: {
_tag: Schema.tag<"User">;
name: typeof Schema.String;
age: typeof Schema.Number;
}): Schema.Struct<...> (+1 overload)
namespace Struct
Struct({4 (property) _tag: Schema.tag<"User">
_tag: import Schema
Schema.const tag: <"User">(tag: "User") => Schema.tag<"User">
Returns a property signature that represents a tag.
A tag is a literal value that is used to distinguish between different types of objects.
The tag is optional when using the `make` method.
tag("User"),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// { readonly _tag: "User"; readonly name: string; readonly age: number; }10type type Type = {
readonly _tag: "User";
readonly name: string;
readonly age: number;
}
Type = typeof const User: Schema.Struct<{
_tag: Schema.tag<"User">;
name: typeof Schema.String;
age: typeof Schema.Number;
}>
User.(property) Schema<{ readonly _tag: "User"; readonly name: string; readonly age: number; }, { readonly _tag: "User"; readonly name: string; readonly age: number; }, never>.Type: {
readonly _tag: "User";
readonly name: string;
readonly age: number;
}
Type11
12namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(const User: Schema.Struct<{
_tag: Schema.tag<"User">;
name: typeof Schema.String;
age: typeof Schema.Number;
}>
User.(method) TypeLiteral<{ _tag: tag<"User">; name: typeof String$; age: typeof Number$; }, []>.make(props: {
readonly _tag?: "User";
readonly name: string;
readonly age: number;
}, options?: MakeOptions): {
readonly _tag: "User";
readonly name: string;
readonly age: number;
}
make({ (property) name: string
name: "John", (property) age: number
age: 44 }))13/*14Output:15{ _tag: 'User', name: 'John', age: 44 }16*/
In the example above, Schema.tag("User")
attaches a _tag
property to the User
struct schema, effectively labeling objects of this struct type as “User”.
This label is automatically applied when using the make
method to create new instances, simplifying object creation and ensuring consistent tagging.
The Schema.TaggedStruct
constructor streamlines the process of creating tagged structs by directly integrating the tag into the struct definition. This method provides a clearer and more declarative approach to building data structures with embedded discriminators.
Example
1import { import Schema
Schema } from "effect"2
3const const User: Schema.TaggedStruct<"User", {
name: typeof Schema.String;
age: typeof Schema.Number;
}>
User = import Schema
Schema.const TaggedStruct: <"User", {
name: typeof Schema.String;
age: typeof Schema.Number;
}>(value: "User", fields: {
name: typeof Schema.String;
age: typeof Schema.Number;
}) => Schema.TaggedStruct<"User", {
name: typeof Schema.String;
age: typeof Schema.Number;
}>
A tagged struct is a struct that has a tag property that is used to distinguish between different types of objects.
The tag is optional when using the `make` method.
TaggedStruct("User", {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// `_tag` is optional9namespace 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 User: Schema.TaggedStruct<"User", {
name: typeof Schema.String;
age: typeof Schema.Number;
}>
User.(method) TypeLiteral<{ _tag: tag<"User">; } & { name: typeof String$; age: typeof Number$; }, []>.make(props: {
readonly name: string;
readonly age: number;
readonly _tag?: "User";
}, options?: MakeOptions): {
readonly name: string;
readonly age: number;
readonly _tag: "User";
}
make({ (property) name: string
name: "John", (property) age: number
age: 44 }))10/*11Output:12{ _tag: 'User', name: 'John', age: 44 }13*/
While a primary tag is often sufficient, TypeScript allows you to define multiple tags for more complex data structuring needs. Here’s an example demonstrating the use of multiple tags within a single struct:
1import { import Schema
Schema } from "effect"2
3const const Product: Schema.TaggedStruct<"Product", {
category: Schema.tag<"Electronics">;
name: typeof Schema.String;
price: typeof Schema.Number;
}>
Product = import Schema
Schema.const TaggedStruct: <"Product", {
category: Schema.tag<"Electronics">;
name: typeof Schema.String;
price: typeof Schema.Number;
}>(value: "Product", fields: {
category: Schema.tag<"Electronics">;
name: typeof Schema.String;
price: typeof Schema.Number;
}) => Schema.TaggedStruct<...>
A tagged struct is a struct that has a tag property that is used to distinguish between different types of objects.
The tag is optional when using the `make` method.
TaggedStruct("Product", {4 (property) category: Schema.tag<"Electronics">
category: import Schema
Schema.const tag: <"Electronics">(tag: "Electronics") => Schema.tag<"Electronics">
Returns a property signature that represents a tag.
A tag is a literal value that is used to distinguish between different types of objects.
The tag is optional when using the `make` method.
tag("Electronics"),5 (property) name: typeof Schema.String
name: import Schema
Schema.(alias) class String
export String
String,6 (property) price: typeof Schema.Number
price: import Schema
Schema.(alias) class Number
export Number
Number7})8
9// `_tag` and `category` are optional10namespace 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 Product: Schema.TaggedStruct<"Product", {
category: Schema.tag<"Electronics">;
name: typeof Schema.String;
price: typeof Schema.Number;
}>
Product.(method) TypeLiteral<{ _tag: tag<"Product">; } & { category: tag<"Electronics">; name: typeof String$; price: typeof Number$; }, []>.make(props: {
readonly category?: "Electronics";
readonly name: string;
readonly price: number;
readonly _tag?: "Product";
}, options?: MakeOptions): {
readonly category: "Electronics";
readonly name: string;
readonly price: number;
readonly _tag: "Product";
}
make({ (property) name: string
name: "Smartphone", (property) price: number
price: 999 }))11/*12Output:13{14 _tag: 'Product',15 category: 'Electronics',16 name: 'Smartphone',17 price: 99918}19*/
This example showcases a product schema that not only categorizes each product under a general tag ("Product"
) but also specifies a category tag ("Electronics"
), enhancing the clarity and specificity of the data model.
When you need to define a schema for your custom data type defined through a class
, the most convenient and fast way is to use the Schema.instanceOf
constructor.
Example
1import { import Schema
Schema } from "effect"2
3class class MyData
MyData {4 constructor(readonly (property) MyData.name: string
name: string) {}5}6
7const const MyDataSchema: Schema.instanceOf<MyData>
MyDataSchema = import Schema
Schema.const instanceOf: <typeof MyData>(constructor: typeof MyData, annotations?: Schema.Annotations.Schema<MyData, readonly []> | undefined) => Schema.instanceOf<MyData>
instanceOf(class MyData
MyData)8
9// MyData10type type Type = MyData
Type = typeof const MyDataSchema: Schema.instanceOf<MyData>
MyDataSchema.(property) Schema<MyData, MyData, never>.Type: MyData
Type11
12namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(import Schema
Schema.(alias) decodeUnknownSync<MyData, MyData>(schema: Schema.Schema<MyData, MyData, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => MyData
export decodeUnknownSync
decodeUnknownSync(const MyDataSchema: Schema.instanceOf<MyData>
MyDataSchema)(new constructor MyData(name: string): MyData
MyData("name")))13// Output: MyData { name: 'name' }14
15namespace 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<MyData, MyData>(schema: Schema.Schema<MyData, MyData, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => MyData
export decodeUnknownSync
decodeUnknownSync(const MyDataSchema: Schema.instanceOf<MyData>
MyDataSchema)({ (property) name: string
name: "name" }))16/*17throws18ParseError: Expected MyData, actual {"name":"name"}19*/
The Schema.instanceOf
constructor is just a lightweight wrapper of the Schema.declare API, which is the primitive in effect/Schema
for declaring new custom data types.
However, note that Schema.instanceOf
can only be used for classes that expose a public constructor.
If you try to use it with classes that, for some reason, have marked the constructor as private
, you’ll receive a TypeScript error:
1import { import Schema
Schema } from "effect"2
3class class MyData
MyData {4 static (property) MyData.make: (name: string) => MyData
make = ((parameter) name: string
name: string) => new constructor MyData(name: string): MyData
MyData((parameter) name: string
name)5 private constructor(readonly (property) MyData.name: string
name: string) {}6}7
8// @ts-expect-error9const const MyDataSchema: Schema.instanceOf<any>
MyDataSchema = import Schema
Schema.const instanceOf: <abstract new (...args: any) => any>(constructor: abstract new (...args: any) => any, annotations?: Schema.Annotations.Schema<any, readonly []> | undefined) => Schema.instanceOf<any>
instanceOf(class MyData
MyData)10/*11Argument of type 'typeof MyData' is not assignable to parameter of type 'abstract new (...args: any) => any'.12 Cannot assign a 'private' constructor type to a 'public' constructor type.ts(2345)13*/
In such cases, you cannot use Schema.instanceOf
, and you must rely on Schema.declare like this:
1import { import Schema
Schema } from "effect"2
3class class MyData
MyData {4 static (property) MyData.make: (name: string) => MyData
make = ((parameter) name: string
name: string) => new constructor MyData(name: string): MyData
MyData((parameter) name: string
name)5 private constructor(readonly (property) MyData.name: string
name: string) {}6}7
8const const MyDataSchema: Schema.SchemaClass<MyData, MyData, never>
MyDataSchema = import Schema
Schema.const declare: <MyData>(is: (input: unknown) => input is MyData, annotations?: Schema.Annotations.Schema<MyData, readonly []> | undefined) => Schema.SchemaClass<MyData, MyData, never> (+1 overload)
The constraint `R extends Schema.Context<P[number]>` enforces dependencies solely from `typeParameters`.
This ensures that when you call `Schema.to` or `Schema.from`, you receive a schema with a `never` context.
declare(9 ((parameter) input: unknown
input: unknown): (parameter) input: unknown
input is class MyData
MyData => (parameter) input: unknown
input instanceof class MyData
MyData10).(method) Annotable<SchemaClass<MyData, MyData, never>, MyData, MyData, never>.annotations(annotations: Schema.Annotations.Schema<MyData, readonly []>): Schema.SchemaClass<MyData, MyData, never>
Merges a set of new annotations with existing ones, potentially overwriting
any duplicates.
annotations({ (property) Annotations.Schema<MyData, readonly []>.identifier?: string
identifier: "MyData" })11
12namespace console
var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v22.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v22.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
console.(method) Console.log(message?: any, ...optionalParams: any[]): void
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v22.x/api/util.html#utilformatformat-args) for more information.
log(import Schema
Schema.(alias) decodeUnknownSync<MyData, MyData>(schema: Schema.Schema<MyData, MyData, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => MyData
export decodeUnknownSync
decodeUnknownSync(const MyDataSchema: Schema.SchemaClass<MyData, MyData, never>
MyDataSchema)(class MyData
MyData.(property) MyData.make: (name: string) => MyData
make("name")))13// Output: MyData { name: 'name' }14
15namespace 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<MyData, MyData>(schema: Schema.Schema<MyData, MyData, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => MyData
export decodeUnknownSync
decodeUnknownSync(const MyDataSchema: Schema.SchemaClass<MyData, MyData, never>
MyDataSchema)({ (property) name: string
name: "name" }))16/*17throws18ParseError: Expected MyData, actual {"name":"name"}19*/
The pick
static function available on each struct schema can be used to create a new Struct
by selecting specific properties from an existing Struct
.
Example (Picking Properties from a Struct)
1import { import Schema
Schema } from "effect"2
3// Define a struct schema with properties "a", "b", and "c"4const const MyStruct: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}>
MyStruct = import Schema
Schema.function Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}>(fields: {
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}): Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}> (+1 overload)
namespace Struct
Struct({5 (property) a: typeof Schema.String
a: import Schema
Schema.(alias) class String
export String
String,6 (property) b: typeof Schema.Number
b: import Schema
Schema.(alias) class Number
export Number
Number,7 (property) c: typeof Schema.Boolean
c: import Schema
Schema.(alias) class Boolean
export Boolean
Boolean8})9
10// Create a new schema that picks properties "a" and "c"11const const PickedSchema: Schema.Struct<{
a: typeof Schema.String;
c: typeof Schema.Boolean;
}>
PickedSchema = const MyStruct: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}>
MyStruct.(method) Struct<{ a: typeof String$; b: typeof Number$; c: typeof Boolean$; }>.pick<["a", "c"]>(keys_0: "a", keys_1: "c"): Schema.Struct<{
a: typeof Schema.String;
c: typeof Schema.Boolean;
}>
pick("a", "c")12// ^? const PickedSchema: Schema.Struct<{13// a: typeof Schema.String;14// c: typeof Schema.Boolean;15// }>
The Schema.pick
function can be applied more broadly beyond just Struct
types, such as with unions of schemas.
However it returns a generic SchemaClass
.
Example (Picking Properties from a Union)
1import { import Schema
Schema } from "effect"2
3// Define a union of two struct schemas4const const MyUnion: Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>]>
MyUnion = import Schema
Schema.function Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>]>(members_0: Schema.Struct<...>, members_1: Schema.Struct<...>): Schema.Union<...> (+3 overloads)
Union(5 import Schema
Schema.function Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>(fields: {
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}): Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}> (+1 overload)
namespace Struct
Struct({ (property) a: typeof Schema.String
a: import Schema
Schema.(alias) class String
export String
String, (property) b: typeof Schema.String
b: import Schema
Schema.(alias) class String
export String
String, (property) c: typeof Schema.String
c: import Schema
Schema.(alias) class String
export String
String }),6 import Schema
Schema.function Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>(fields: {
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}): Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({ (property) a: typeof Schema.Number
a: import Schema
Schema.(alias) class Number
export Number
Number, (property) b: typeof Schema.Number
b: import Schema
Schema.(alias) class Number
export Number
Number, (property) d: typeof Schema.Number
d: import Schema
Schema.(alias) class Number
export Number
Number })7)8
9// Create a new schema that picks properties "a" and "b"10const const PickedSchema: Schema.SchemaClass<{
readonly a: string | number;
readonly b: string | number;
}, {
readonly a: string | number;
readonly b: string | number;
}, never>
PickedSchema = const MyUnion: Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>]>
MyUnion.(method) Pipeable.pipe<Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>]>, Schema.SchemaClass<...>>(this: Schema.Union<...>, ab: (_: Schema.Union<...>) => Schema.SchemaClass<...>): Schema.SchemaClass<...> (+21 overloads)
pipe(import Schema
Schema.const pick: <{
readonly a: string;
readonly b: string;
readonly c: string;
} | {
readonly a: number;
readonly b: number;
readonly d: number;
}, {
readonly a: string;
readonly b: string;
readonly c: string;
} | {
...;
}, [...]>(keys_0: "a", keys_1: "b") => <R>(self: Schema.Schema<...>) => Schema.SchemaClass<...>
pick("a", "b"))11// ^? const PickedSchema: Schema.SchemaClass<{12// readonly a: string | number;13// readonly b: string | number;14// }>
The omit
static function available in each struct schema can be used to create a new Struct
by excluding particular properties from an existing Struct
.
Example (Omitting Properties from a Struct)
1import { import Schema
Schema } from "effect"2
3// Define a struct schema with properties "a", "b", and "c"4const const MyStruct: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}>
MyStruct = import Schema
Schema.function Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}>(fields: {
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}): Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}> (+1 overload)
namespace Struct
Struct({5 (property) a: typeof Schema.String
a: import Schema
Schema.(alias) class String
export String
String,6 (property) b: typeof Schema.Number
b: import Schema
Schema.(alias) class Number
export Number
Number,7 (property) c: typeof Schema.Boolean
c: import Schema
Schema.(alias) class Boolean
export Boolean
Boolean8})9
10// Create a new schema that omits property "b"11const const PickedSchema: Schema.Struct<{
a: typeof Schema.String;
c: typeof Schema.Boolean;
}>
PickedSchema = const MyStruct: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
c: typeof Schema.Boolean;
}>
MyStruct.(method) Struct<{ a: typeof String$; b: typeof Number$; c: typeof Boolean$; }>.omit<["b"]>(keys_0: "b"): Schema.Struct<{
a: typeof Schema.String;
c: typeof Schema.Boolean;
}>
omit("b")12// ^? const PickedSchema: Schema.Struct<{13// a: typeof Schema.String;14// c: typeof Schema.Boolean;15// }>
The Schema.omit
function can be applied more broadly beyond just Struct
types, such as with unions of schemas.
However it returns a generic Schema
.
Example (Omitting Properties from a Union)
1import { import Schema
Schema } from "effect"2
3// Define a union of two struct schemas4const const MyUnion: Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>]>
MyUnion = import Schema
Schema.function Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>]>(members_0: Schema.Struct<...>, members_1: Schema.Struct<...>): Schema.Union<...> (+3 overloads)
Union(5 import Schema
Schema.function Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>(fields: {
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}): Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}> (+1 overload)
namespace Struct
Struct({ (property) a: typeof Schema.String
a: import Schema
Schema.(alias) class String
export String
String, (property) b: typeof Schema.String
b: import Schema
Schema.(alias) class String
export String
String, (property) c: typeof Schema.String
c: import Schema
Schema.(alias) class String
export String
String }),6 import Schema
Schema.function Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>(fields: {
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}): Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({ (property) a: typeof Schema.Number
a: import Schema
Schema.(alias) class Number
export Number
Number, (property) b: typeof Schema.Number
b: import Schema
Schema.(alias) class Number
export Number
Number, (property) d: typeof Schema.Number
d: import Schema
Schema.(alias) class Number
export Number
Number })7)8
9// Create a new schema that omits property "b"10const const PickedSchema: Schema.SchemaClass<{
readonly a: string | number;
}, {
readonly a: string | number;
}, never>
PickedSchema = const MyUnion: Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>]>
MyUnion.(method) Pipeable.pipe<Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.String;
c: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.Number;
b: typeof Schema.Number;
d: typeof Schema.Number;
}>]>, Schema.SchemaClass<...>>(this: Schema.Union<...>, ab: (_: Schema.Union<...>) => Schema.SchemaClass<...>): Schema.SchemaClass<...> (+21 overloads)
pipe(import Schema
Schema.const omit: <{
readonly a: string;
readonly b: string;
readonly c: string;
} | {
readonly a: number;
readonly b: number;
readonly d: number;
}, {
readonly a: string;
readonly b: string;
readonly c: string;
} | {
...;
}, [...]>(keys_0: "b") => <R>(self: Schema.Schema<...>) => Schema.SchemaClass<...>
omit("b"))11// ^? const PickedSchema: Schema.SchemaClass<{12// readonly a: string | number;13// }>
The Schema.partial
function makes all properties within a schema optional.
Example
1import { import Schema
Schema } from "effect"2
3// Create a schema with an optional property "a"4const const schema: Schema.SchemaClass<{
readonly a?: string | undefined;
}, {
readonly a?: string | undefined;
}, never>
schema = import Schema
Schema.const partial: <{
readonly a: string;
}, {
readonly a: string;
}, never>(self: Schema.Schema<{
readonly a: string;
}, {
readonly a: string;
}, never>) => Schema.SchemaClass<{
readonly a?: string | undefined;
}, {
readonly a?: string | undefined;
}, never>
partial(import Schema
Schema.function Struct<{
a: typeof Schema.String;
}>(fields: {
a: typeof Schema.String;
}): Schema.Struct<{
a: typeof Schema.String;
}> (+1 overload)
namespace Struct
Struct({ (property) a: typeof Schema.String
a: import Schema
Schema.(alias) class String
export String
String }))5
6// { readonly a?: string | undefined; }7type type Type = {
readonly a?: string | undefined;
}
Type = typeof const schema: Schema.SchemaClass<{
readonly a?: string | undefined;
}, {
readonly a?: string | undefined;
}, never>
schema.(property) Schema<{ readonly a?: string | undefined; }, { readonly a?: string | undefined; }, never>.Type: {
readonly a?: string | undefined;
}
Type
By default, the Schema.partial
operation adds undefined
to the type of each property. If you want to avoid this, you can use Schema.partialWith
and pass { exact: true }
as an argument.
Example (Creating an Exact Partial Schema)
1import { import Schema
Schema } from "effect"2
3// Create a schema with an optional property "a" without allowing undefined4const const schema: Schema.SchemaClass<{
readonly a?: string;
}, {
readonly a?: string;
}, never>
schema = import Schema
Schema.const partialWith: <{
readonly a: string;
}, {
readonly a: string;
}, never, {
readonly exact: true;
}>(self: Schema.Schema<{
readonly a: string;
}, {
readonly a: string;
}, never>, options: {
readonly exact: true;
}) => Schema.SchemaClass<...> (+1 overload)
partialWith(5 import Schema
Schema.function Struct<{
a: typeof Schema.String;
}>(fields: {
a: typeof Schema.String;
}): Schema.Struct<{
a: typeof Schema.String;
}> (+1 overload)
namespace Struct
Struct({6 (property) a: typeof Schema.String
a: import Schema
Schema.(alias) class String
export String
String7 }),8 { (property) exact: true
exact: true }9)10
11// { readonly a?: string; }12type type Type = {
readonly a?: string;
}
Type = typeof const schema: Schema.SchemaClass<{
readonly a?: string;
}, {
readonly a?: string;
}, never>
schema.(property) Schema<{ readonly a?: string; }, { readonly a?: string; }, never>.Type: {
readonly a?: string;
}
Type
The Schema.required
function ensures that all properties in a schema are mandatory.
Example
1import { import Schema
Schema } from "effect"2
3// Create a schema and make all properties required4const const schema: Schema.SchemaClass<{
readonly a: string;
readonly b: number;
}, {
readonly a: string;
readonly b: number;
}, never>
schema = import Schema
Schema.const required: <{
readonly a?: string;
readonly b?: number;
}, {
readonly a?: string;
readonly b?: number;
}, never>(self: Schema.Schema<{
readonly a?: string;
readonly b?: number;
}, {
readonly a?: string;
readonly b?: number;
}, never>) => Schema.SchemaClass<...>
required(5 import Schema
Schema.function Struct<{
a: Schema.optionalWith<typeof Schema.String, {
exact: true;
}>;
b: Schema.optionalWith<typeof Schema.Number, {
exact: true;
}>;
}>(fields: {
a: Schema.optionalWith<typeof Schema.String, {
exact: true;
}>;
b: Schema.optionalWith<...>;
}): Schema.Struct<...> (+1 overload)
namespace Struct
Struct({6 (property) a: Schema.optionalWith<typeof Schema.String, {
exact: true;
}>
a: import Schema
Schema.const optionalWith: <typeof Schema.String, {
exact: true;
}>(self: typeof Schema.String, options: {
exact: true;
}) => Schema.optionalWith<typeof Schema.String, {
exact: true;
}> (+1 overload)
optionalWith(import Schema
Schema.(alias) class String
export String
String, { (property) exact: true
exact: true }),7 (property) b: Schema.optionalWith<typeof Schema.Number, {
exact: true;
}>
b: import Schema
Schema.const optionalWith: <typeof Schema.Number, {
exact: true;
}>(self: typeof Schema.Number, options: {
exact: true;
}) => Schema.optionalWith<typeof Schema.Number, {
exact: true;
}> (+1 overload)
optionalWith(import Schema
Schema.(alias) class Number
export Number
Number, { (property) exact: true
exact: true })8 })9)10
11// { readonly a: string; readonly b: number; }12type type Type = {
readonly a: string;
readonly b: number;
}
Type = typeof const schema: Schema.SchemaClass<{
readonly a: string;
readonly b: number;
}, {
readonly a: string;
readonly b: number;
}, never>
schema.(property) Schema<{ readonly a: string; readonly b: number; }, { readonly a: string; readonly b: number; }, never>.Type: {
readonly a: string;
readonly b: number;
}
Type
In this example, both a
and b
are made required, even though they were initially defined as optional.
The Schema.keyof
operation creates a schema that represents the keys of a given object schema.
Example
1import { import Schema
Schema } from "effect"2
3const const schema: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>
schema = import Schema
Schema.function Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>(fields: {
a: typeof Schema.String;
b: typeof Schema.Number;
}): Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}> (+1 overload)
namespace Struct
Struct({4 (property) a: typeof Schema.String
a: import Schema
Schema.(alias) class String
export String
String,5 (property) b: typeof Schema.Number
b: import Schema
Schema.(alias) class Number
export Number
Number6})7
8const const keys: Schema.SchemaClass<"a" | "b", "a" | "b", never>
keys = import Schema
Schema.const keyof: <{
readonly a: string;
readonly b: number;
}, {
readonly a: string;
readonly b: number;
}, never>(self: Schema.Schema<{
readonly a: string;
readonly b: number;
}, {
readonly a: string;
readonly b: number;
}, never>) => Schema.SchemaClass<...>
keyof(const schema: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>
schema)9
10// "a" | "b"11type type Type = "a" | "b"
Type = typeof const keys: Schema.SchemaClass<"a" | "b", "a" | "b", never>
keys.(property) Schema<"a" | "b", "a" | "b", never>.Type: "a" | "b"
Type