Skip to content

Basic Usage

The Schema module provides built-in schemas for common primitive types.

SchemaEquivalent TypeScript Type
Schema.Stringstring
Schema.Numbernumber
Schema.Booleanboolean
Schema.BigIntFromSelfBigInt
Schema.SymbolFromSelfsymbol
Schema.Objectobject
Schema.Undefinedundefined
Schema.Voidvoid
Schema.Anyany
Schema.Unknownunknown
Schema.Nevernever

Example (Using a Primitive Schema)

import {
import Schema
Schema
} from "effect"
const
const schema: typeof Schema.String
schema
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
// Infers the type as string
//
// ┌─── string
// ▼
type
type Type = string
Type
= typeof
const schema: typeof Schema.String
schema
.
Schema<string, string, never>.Type: string
Type
// Attempt to decode a null value, which will throw a parse error
import Schema
Schema
.
decodeUnknownSync<string, string>(schema: Schema.Schema<string, string, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => string
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: typeof Schema.String
schema
)(null)
/*
throws:
ParseError: Expected string, actual null
*/

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 (Expanding a Schema with asSchema)

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>.

import {
import Schema
Schema
} from "effect"
// ┌─── typeof Schema.String
// ▼
const
const schema: typeof Schema.String
schema
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
// ┌─── Schema<string, string, never>
// ▼
const
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>

@since3.10.0

asSchema
(
const schema: typeof Schema.String
schema
)

You can create a schema for unique symbols using Schema.UniqueSymbolFromSelf.

Example (Creating a Schema for a Unique Symbol)

import {
import Schema
Schema
} from "effect"
const
const mySymbol: typeof mySymbol
mySymbol
=
var Symbol: SymbolConstructor
Symbol
.
SymbolConstructor.for(key: string): symbol

Returns a Symbol object from the global symbol registry matching the given key if found. Otherwise, returns a new symbol with this key.

@paramkey key to search for.

for
("mySymbol")
const
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>

@since3.10.0

UniqueSymbolFromSelf
(
const mySymbol: typeof mySymbol
mySymbol
)
// ┌─── typeof mySymbol
// ▼
type
type Type = typeof mySymbol
Type
= typeof
const schema: Schema.SchemaClass<typeof mySymbol, typeof mySymbol, never>
schema
.
Schema<typeof mySymbol, typeof mySymbol, never>.Type: typeof mySymbol
Type
import Schema
Schema
.
decodeUnknownSync<typeof mySymbol, typeof mySymbol>(schema: Schema.Schema<typeof mySymbol, typeof mySymbol, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => typeof mySymbol
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.SchemaClass<typeof mySymbol, typeof mySymbol, never>
schema
)(null)
/*
throws:
ParseError: Expected Symbol(mySymbol), actual null
*/

Literal schemas represent a literal type. You can use them to specify exact values that a type must have.

Literals can be of the following types:

  • string
  • number
  • boolean
  • null
  • bigint

Example (Defining Literal Schemas)

import {
import Schema
Schema
} from "effect"
// Define various literal schemas
import Schema
Schema
.
class Null

@since3.10.0

Null
// Same as S.Literal(null)
import Schema
Schema
.
function Literal<["a"]>(literals_0: "a"): Schema.Literal<["a"]> (+2 overloads)

@since3.10.0

Literal
("a") // string literal
import Schema
Schema
.
function Literal<[1]>(literals_0: 1): Schema.Literal<[1]> (+2 overloads)

@since3.10.0

Literal
(1) // number literal
import Schema
Schema
.
function Literal<[true]>(literals_0: true): Schema.Literal<[true]> (+2 overloads)

@since3.10.0

Literal
(true) // boolean literal
import Schema
Schema
.
function Literal<[2n]>(literals_0: 2n): Schema.Literal<[2n]> (+2 overloads)

@since3.10.0

Literal
(2n) // BigInt literal

Example (Defining a Literal Schema for "a")

import {
import Schema
Schema
} from "effect"
// ┌─── Literal<["a"]>
// ▼
const
const schema: Schema.Literal<["a"]>
schema
=
import Schema
Schema
.
function Literal<["a"]>(literals_0: "a"): Schema.Literal<["a"]> (+2 overloads)

@since3.10.0

Literal
("a")
// ┌─── "a"
// ▼
type
type Type = "a"
Type
= typeof
const schema: Schema.Literal<["a"]>
schema
.
Schema<"a", "a", never>.Type: "a"
Type
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<"a", "a">(schema: Schema.Schema<"a", "a", never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => "a"
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Literal<["a"]>
schema
)("a"))
// Output: "a"
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<"a", "a">(schema: Schema.Schema<"a", "a", never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => "a"
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Literal<["a"]>
schema
)("b"))
/*
throws:
ParseError: Expected "a", actual "b"
*/

You can create a union of multiple literals by passing them as arguments to the Schema.Literal constructor:

Example (Defining a Union of Literals)

import {
import Schema
Schema
} from "effect"
// ┌─── Literal<["a", "b", "c"]>
// ▼
const
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)

@since3.10.0

Literal
("a", "b", "c")
// ┌─── "a" | "b" | "c"
// ▼
type
type Type = "a" | "b" | "c"
Type
= typeof
const schema: Schema.Literal<["a", "b", "c"]>
schema
.
Schema<"a" | "b" | "c", "a" | "b" | "c", never>.Type: "a" | "b" | "c"
Type
import Schema
Schema
.
decodeUnknownSync<"a" | "b" | "c", "a" | "b" | "c">(schema: Schema.Schema<"a" | "b" | "c", "a" | "b" | "c", never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => "a" | ... 1 more ... | "c"
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const schema: Schema.Literal<["a", "b", "c"]>
schema
)(null)
/*
throws:
ParseError: "a" | "b" | "c"
├─ Expected "a", actual null
├─ Expected "b", actual null
└─ Expected "c", actual null
*/

If you want to set a custom error message for the entire union of literals, you can use the override: true option (see Custom Error Messages for more details) to specify a unified message.

Example (Adding a Custom Message to a Union of Literals)

import {
import Schema
Schema
} from "effect"
// Schema with individual messages for each literal
const
const individualMessages: Schema.Literal<["a", "b", "c"]>
individualMessages
=
import Schema
Schema
.
function Literal<["a", "b", "c"]>(literals_0: "a", literals_1: "b", literals_2: "c"): Schema.Literal<["a", "b", "c"]> (+2 overloads)

@since3.10.0

Literal
("a", "b", "c")
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<"a" | "b" | "c", "a" | "b" | "c">(schema: Schema.Schema<"a" | "b" | "c", "a" | "b" | "c", never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => "a" | ... 1 more ... | "c"
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const individualMessages: Schema.Literal<["a", "b", "c"]>
individualMessages
)(null))
/*
throws:
ParseError: "a" | "b" | "c"
├─ Expected "a", actual null
├─ Expected "b", actual null
└─ Expected "c", actual null
*/
// Schema with a unified custom message for all literals
const
const unifiedMessage: Schema.Literal<["a", "b", "c"]>
unifiedMessage
=
import Schema
Schema
.
function Literal<["a", "b", "c"]>(literals_0: "a", literals_1: "b", literals_2: "c"): Schema.Literal<["a", "b", "c"]> (+2 overloads)

@since3.10.0

Literal
("a", "b", "c").
Annotable<Literal<["a", "b", "c"]>, "a" | "b" | "c", "a" | "b" | "c", never>.annotations(annotations: Schema.Annotations.GenericSchema<"a" | "b" | "c">): Schema.Literal<["a", "b", "c"]>

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

annotations
({
Annotations.Schema<"a" | "b" | "c", readonly []>.message?: MessageAnnotation
message
: () => ({
message: string | Effect<string, never, never>
message
: "Not a valid code",
override: boolean
override
: true })
})
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<"a" | "b" | "c", "a" | "b" | "c">(schema: Schema.Schema<"a" | "b" | "c", "a" | "b" | "c", never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => "a" | ... 1 more ... | "c"
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const unifiedMessage: Schema.Literal<["a", "b", "c"]>
unifiedMessage
)(null))
/*
throws:
ParseError: Not a valid code
*/

You can access the literals defined in a literal schema using the literals property:

import {
import Schema
Schema
} from "effect"
const
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)

@since3.10.0

Literal
("a", "b", "c")
// ┌─── readonly ["a", "b", "c"]
// ▼
const
const literals: readonly ["a", "b", "c"]
literals
=
const schema: Schema.Literal<["a", "b", "c"]>
schema
.
Literal<["a", "b", "c"]>.literals: readonly ["a", "b", "c"]
literals

You can use Schema.pickLiteral with a literal schema to narrow down its possible values.

Example (Using pickLiteral to Narrow Values)

import {
import Schema
Schema
} from "effect"
// Create a schema for a subset of literals ("a" and "b") from a larger set
//
// ┌─── Literal<["a", "b"]>
// ▼
const
const schema: Schema.Literal<["a", "b"]>
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)

@since3.10.0

Literal
("a", "b", "c").
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.

@example

import * as Schema from "effect/Schema"
import { Either } from "effect"
const schema = Schema.Literal("a", "b", "c").pipe(Schema.pickLiteral("a", "b"))
assert.deepStrictEqual(Schema.decodeSync(schema)("a"), "a")
assert.deepStrictEqual(Schema.decodeSync(schema)("b"), "b")
assert.strictEqual(Either.isLeft(Schema.decodeUnknownEither(schema)("c")), true)

@since3.10.0

pickLiteral
("a", "b")
)

Sometimes, you may need to reuse a literal schema in other parts of your code. Below is an example demonstrating how to do this:

Example (Creating a Subtype from a Literal Schema)

import {
import Schema
Schema
} from "effect"
// Define the base set of fruit categories
const
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)

@since3.10.0

Literal
("sweet", "citrus", "tropical")
// Define a general Fruit schema with the base category set
const
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)

@since3.10.0

Struct
({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
category: Schema.Literal<["sweet", "citrus", "tropical"]>
category
:
const FruitCategory: Schema.Literal<["sweet", "citrus", "tropical"]>
FruitCategory
})
// Define a specific Fruit schema for only "sweet" and "citrus" categories
const
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)

@since3.10.0

Struct
({
id: typeof Schema.Number
id
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
,
category: Schema.Literal<["sweet", "citrus"]>
category
:
const FruitCategory: Schema.Literal<["sweet", "citrus", "tropical"]>
FruitCategory
.
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.

@example

import * as Schema from "effect/Schema"
import { Either } from "effect"
const schema = Schema.Literal("a", "b", "c").pipe(Schema.pickLiteral("a", "b"))
assert.deepStrictEqual(Schema.decodeSync(schema)("a"), "a")
assert.deepStrictEqual(Schema.decodeSync(schema)("b"), "b")
assert.strictEqual(Either.isLeft(Schema.decodeUnknownEither(schema)("c")), true)

@since3.10.0

pickLiteral
("sweet", "citrus"))
})

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 (Defining Template Literals)

import {
import Schema
Schema
} from "effect"
// This creates a schema for: `a${string}`
//
// ┌─── TemplateLiteral<`a${string}`>
// ▼
const
const schema1: Schema.TemplateLiteral<`a${string}`>
schema1
=
import Schema
Schema
.
const TemplateLiteral: <["a", typeof Schema.String]>(head: "a", tail_0: typeof Schema.String) => Schema.TemplateLiteral<`a${string}`>

@since3.10.0

TemplateLiteral
("a",
import Schema
Schema
.
class String
export String

@since3.10.0

String
)
// This creates a schema for:
// `https://${string}.com` | `https://${string}.net`
const
const schema2: Schema.TemplateLiteral<`https://${string}.com` | `https://${string}.net`>
schema2
=
import 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<...>

@since3.10.0

TemplateLiteral
(
"https://",
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
".",
import Schema
Schema
.
function Literal<["com", "net"]>(literals_0: "com", literals_1: "net"): Schema.Literal<["com", "net"]> (+2 overloads)

@since3.10.0

Literal
("com", "net")
)

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:

import {
import Schema
Schema
} from "effect"
const
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)

@since3.10.0

Literal
("welcome_email", "email_heading")
const
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)

@since3.10.0

Literal
("footer_title", "footer_sendoff")
// This creates a schema for:
// "welcome_email_id" | "email_heading_id" |
// "footer_title_id" | "footer_sendoff_id"
const
const schema: Schema.TemplateLiteral<"welcome_email_id" | "email_heading_id" | "footer_title_id" | "footer_sendoff_id">
schema
=
import 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<...>

@since3.10.0

TemplateLiteral
(
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)

@since3.10.0

Union
(
const EmailLocaleIDs: Schema.Literal<["welcome_email", "email_heading"]>
EmailLocaleIDs
,
const FooterLocaleIDs: Schema.Literal<["footer_title", "footer_sendoff"]>
FooterLocaleIDs
),
"_id"
)

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 by Schema.Literal or used directly
  • Unions of the above types
  • Brands of the above types

Example (Using a Branded String in a Template Literal)

import {
import Schema
Schema
} from "effect"
// Create a branded string schema for an authorization token
const
const AuthorizationToken: Schema.brand<typeof Schema.String, "AuthorizationToken">
AuthorizationToken
=
import Schema
Schema
.
class String
export String

@since3.10.0

String
.
Pipeable.pipe<typeof Schema.String, Schema.brand<typeof Schema.String, "AuthorizationToken">>(this: typeof Schema.String, ab: (_: typeof Schema.String) => Schema.brand<typeof Schema.String, "AuthorizationToken">): Schema.brand<...> (+21 overloads)
pipe
(
import Schema
Schema
.
const brand: <typeof Schema.String, "AuthorizationToken">(brand: "AuthorizationToken", annotations?: Schema.Annotations.Schema<string & Brand<"AuthorizationToken">, readonly []> | undefined) => (self: typeof Schema.String) => Schema.brand<...>

Returns a nominal branded schema by applying a brand to a given schema.

Schema<A> + B -> Schema<A & Brand<B>>

@paramself - The input schema to be combined with the brand.

@parambrand - The brand to apply.

@example

import * as Schema from "effect/Schema"
const Int = Schema.Number.pipe(Schema.int(), Schema.brand("Int"))
type Int = Schema.Schema.Type<typeof Int> // number & Brand<"Int">

@since3.10.0

brand
("AuthorizationToken")
)
// This creates a schema for:
// `Bearer ${string & Brand<"AuthorizationToken">}`
const
const schema: Schema.TemplateLiteral<`Bearer ${string & Brand<"AuthorizationToken">}`>
schema
=
import Schema
Schema
.
const TemplateLiteral: <["Bearer ", Schema.brand<typeof Schema.String, "AuthorizationToken">]>(head: "Bearer ", tail_0: Schema.brand<typeof Schema.String, "AuthorizationToken">) => Schema.TemplateLiteral<...>

@since3.10.0

TemplateLiteral
("Bearer ",
const AuthorizationToken: Schema.brand<typeof Schema.String, "AuthorizationToken">
AuthorizationToken
)

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.

The Schema.TemplateLiteralParser constructor supports the same types of spans as Schema.TemplateLiteral.

Example (Using TemplateLiteralParser for Parsing and Encoding)

import {
import Schema
Schema
} from "effect"
// ┌─── Schema<readonly [number, "a", string], `${string}a${string}`>
// ▼
const
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<...>

@since3.10.0

TemplateLiteralParser
(
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".

@since3.10.0

NumberFromString
,
"a",
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
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

@since3.10.0

decodeSync
(
const schema: Schema.TemplateLiteralParser<[typeof Schema.NumberFromString, "a", typeof Schema.NonEmptyString]>
schema
)("100afoo"))
// Output: [ 100, 'a', 'foo' ]
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
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

@since3.10.0

encodeSync
(
const schema: Schema.TemplateLiteralParser<[typeof Schema.NumberFromString, "a", typeof Schema.NonEmptyString]>
schema
)([100, "a", "foo"]))
// 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 (Defining a Schema for an Enum)

import {
import Schema
Schema
} from "effect"
enum
enum Fruits
Fruits
{
function (enum member) Fruits.Apple = 0
Apple
,
function (enum member) Fruits.Banana = 1
Banana
}
// ┌─── Enums<typeof Fruits>
// ▼
const
const schema: Schema.Enums<typeof Fruits>
schema
=
import Schema
Schema
.
const Enums: <typeof Fruits>(enums: typeof Fruits) => Schema.Enums<typeof Fruits>

@since3.10.0

Enums
(
enum Fruits
Fruits
)
//
// ┌─── Fruits
// ▼
type
type Type = Fruits
Type
= typeof
const schema: Schema.Enums<typeof Fruits>
schema
.
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.

import {
import Schema
Schema
} from "effect"
enum
enum Fruits
Fruits
{
function (enum member) Fruits.Apple = 0
Apple
,
function (enum member) Fruits.Banana = 1
Banana
}
const
const schema: Schema.Enums<typeof Fruits>
schema
=
import Schema
Schema
.
const Enums: <typeof Fruits>(enums: typeof Fruits) => Schema.Enums<typeof Fruits>

@since3.10.0

Enums
(
enum Fruits
Fruits
)
const schema: Schema.Enums<typeof Fruits>
schema
.
Enums<typeof Fruits>.enums: typeof Fruits
enums
// Returns all enum members
const schema: Schema.Enums<typeof Fruits>
schema
.
Enums<typeof Fruits>.enums: typeof Fruits
enums
.
function (enum member) Fruits.Apple = 0
Apple
// Access the Apple member
const schema: Schema.Enums<typeof Fruits>
schema
.
Enums<typeof Fruits>.enums: typeof Fruits
enums
.
function (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 (Defining a Union Schema)

import {
import Schema
Schema
} from "effect"
// ┌─── Union<[typeof Schema.String, typeof Schema.Number]>
// ▼
const
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)

@since3.10.0

Union
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
)
// ┌─── string | number
// ▼
type
type Type = string | number
Type
= typeof
const schema: Schema.Union<[typeof Schema.String, typeof Schema.Number]>
schema
.
Schema<string | number, string | number, never>.Type: string | number
Type

When decoding, union members are evaluated in the order they are defined. If a value matches the first member, it will be decoded using that schema. If not, the decoding process moves on to the next member.

If multiple schemas could decode the same value, the order matters. Placing a more general schema before a more specific one may result in missing properties, as the first matching schema will be used.

Example (Handling Overlapping Schemas in a Union)

import {
import Schema
Schema
} from "effect"
// Define two overlapping schemas
const
const Member1: Schema.Struct<{
a: typeof Schema.String;
}>
Member1
=
import Schema
Schema
.
function Struct<{
a: typeof Schema.String;
}>(fields: {
a: typeof Schema.String;
}): Schema.Struct<{
a: typeof Schema.String;
}> (+1 overload)

@since3.10.0

Struct
({
a: typeof Schema.String
a
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
})
const
const Member2: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>
Member2
=
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)

@since3.10.0

Struct
({
a: typeof Schema.String
a
:
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
b: typeof Schema.Number
b
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
// ❌ Define a union where Member1 appears first
const
const Bad: Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>]>
Bad
=
import Schema
Schema
.
function Union<[Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>]>(members_0: Schema.Struct<{
a: typeof Schema.String;
}>, members_1: Schema.Struct<...>): Schema.Union<...> (+3 overloads)

@since3.10.0

Union
(
const Member1: Schema.Struct<{
a: typeof Schema.String;
}>
Member1
,
const Member2: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>
Member2
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}, {
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}>(schema: Schema.Schema<{
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}, {
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Bad: Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
}>, Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>]>
Bad
)({
a: string
a
: "a",
b: number
b
: 12 }))
// Output: { a: 'a' } (Member1 matched first, so `b` was ignored)
// ✅ Define a union where Member2 appears first
const
const Good: Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>, Schema.Struct<{
a: typeof Schema.String;
}>]>
Good
=
import Schema
Schema
.
function Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>, Schema.Struct<{
a: typeof Schema.String;
}>]>(members_0: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>, members_1: Schema.Struct<...>): Schema.Union<...> (+3 overloads)

@since3.10.0

Union
(
const Member2: Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>
Member2
,
const Member1: Schema.Struct<{
a: typeof Schema.String;
}>
Member1
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}, {
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}>(schema: Schema.Schema<{
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}, {
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly a: string;
} | {
readonly a: string;
readonly b: number;
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const Good: Schema.Union<[Schema.Struct<{
a: typeof Schema.String;
b: typeof Schema.Number;
}>, Schema.Struct<{
a: typeof Schema.String;
}>]>
Good
)({
a: string
a
: "a",
b: number
b
: 12 }))
// Output: { a: 'a', b: 12 } (Member2 matched first, so `b` was included)

While you can create a union of literals by combining individual literal schemas:

Example (Using Individual Literal Schemas)

import {
import Schema
Schema
} from "effect"
// ┌─── Union<[Schema.Literal<["a"]>, Schema.Literal<["b"]>, Schema.Literal<["c"]>]>
// ▼
const
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)

@since3.10.0

Union
(
import Schema
Schema
.
function Literal<["a"]>(literals_0: "a"): Schema.Literal<["a"]> (+2 overloads)

@since3.10.0

Literal
("a"),
import Schema
Schema
.
function Literal<["b"]>(literals_0: "b"): Schema.Literal<["b"]> (+2 overloads)

@since3.10.0

Literal
("b"),
import Schema
Schema
.
function Literal<["c"]>(literals_0: "c"): Schema.Literal<["c"]> (+2 overloads)

@since3.10.0

Literal
("c")
)

You can simplify the process by passing multiple literals directly to the Schema.Literal constructor:

Example (Defining a Union of Literals)

import {
import Schema
Schema
} from "effect"
// ┌─── Literal<["a", "b", "c"]>
// ▼
const
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)

@since3.10.0

Literal
("a", "b", "c")
// ┌─── "a" | "b" | "c"
// ▼
type
type Type = "a" | "b" | "c"
Type
= typeof
const schema: Schema.Literal<["a", "b", "c"]>
schema
.
Schema<"a" | "b" | "c", "a" | "b" | "c", never>.Type: "a" | "b" | "c"
Type

If you want to set a custom error message for the entire union of literals, you can use the override: true option (see Custom Error Messages for more details) to specify a unified message.

Example (Adding a Custom Message to a Union of Literals)

import {
import Schema
Schema
} from "effect"
// Schema with individual messages for each literal
const
const individualMessages: Schema.Literal<["a", "b", "c"]>
individualMessages
=
import Schema
Schema
.
function Literal<["a", "b", "c"]>(literals_0: "a", literals_1: "b", literals_2: "c"): Schema.Literal<["a", "b", "c"]> (+2 overloads)

@since3.10.0

Literal
("a", "b", "c")
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<"a" | "b" | "c", "a" | "b" | "c">(schema: Schema.Schema<"a" | "b" | "c", "a" | "b" | "c", never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => "a" | ... 1 more ... | "c"
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const individualMessages: Schema.Literal<["a", "b", "c"]>
individualMessages
)(null))
/*
throws:
ParseError: "a" | "b" | "c"
├─ Expected "a", actual null
├─ Expected "b", actual null
└─ Expected "c", actual null
*/
// Schema with a unified custom message for all literals
const
const unifiedMessage: Schema.Literal<["a", "b", "c"]>
unifiedMessage
=
import Schema
Schema
.
function Literal<["a", "b", "c"]>(literals_0: "a", literals_1: "b", literals_2: "c"): Schema.Literal<["a", "b", "c"]> (+2 overloads)

@since3.10.0

Literal
("a", "b", "c").
Annotable<Literal<["a", "b", "c"]>, "a" | "b" | "c", "a" | "b" | "c", never>.annotations(annotations: Schema.Annotations.GenericSchema<"a" | "b" | "c">): Schema.Literal<["a", "b", "c"]>

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

annotations
({
Annotations.Schema<"a" | "b" | "c", readonly []>.message?: MessageAnnotation
message
: () => ({
message: string | Effect<string, never, never>
message
: "Not a valid code",
override: boolean
override
: true })
})
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<"a" | "b" | "c", "a" | "b" | "c">(schema: Schema.Schema<"a" | "b" | "c", "a" | "b" | "c", never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => "a" | ... 1 more ... | "c"
export decodeUnknownSync

@throwsParseError

@since3.10.0

decodeUnknownSync
(
const unifiedMessage: Schema.Literal<["a", "b", "c"]>
unifiedMessage
)(null))
/*
throws:
ParseError: Not a valid code
*/

The Schema module includes utility functions for defining schemas that allow nullable types, helping to handle values that may be null, undefined, or both.

Example (Creating Nullable Schemas)

import {
import Schema
Schema
} from "effect"
// Represents a schema for a string or null value
import Schema
Schema
.
const NullOr: <typeof Schema.String>(self: typeof Schema.String) => Schema.NullOr<typeof Schema.String>

@since3.10.0

NullOr
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
)
// Represents a schema for a string, null, or undefined value
import Schema
Schema
.
const NullishOr: <typeof Schema.String>(self: typeof Schema.String) => Schema.NullishOr<typeof Schema.String>

@since3.10.0

NullishOr
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
)
// Represents a schema for a string or undefined value
import Schema
Schema
.
const UndefinedOr: <typeof Schema.String>(self: typeof Schema.String) => Schema.UndefinedOr<typeof Schema.String>

@since3.10.0

UndefinedOr
(
import Schema
Schema
.
class String
export String

@since3.10.0

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.

Example (Defining a Discriminated Union in TypeScript)

type
type Circle = {
readonly kind: "circle";
readonly radius: number;
}
Circle
= {
readonly
kind: "circle"
kind
: "circle"
readonly
radius: number
radius
: number
}
type
type Square = {
readonly kind: "square";
readonly sideLength: number;
}
Square
= {
readonly
kind: "square"
kind
: "square"
readonly
sideLength: number
sideLength
: number
}
type
type Shape = Circle | Square
Shape
=
type Circle = {
readonly kind: "circle";
readonly radius: number;
}
Circle
|
type Square = {
readonly kind: "square";
readonly sideLength: number;
}
Square

In the Schema module, you can define a discriminated union similarly by specifying a literal field as the discriminant for each type.

Example (Defining a Discriminated Union Using Schema)

import {
import Schema
Schema
} from "effect"
const
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)

@since3.10.0

Struct
({
kind: Schema.Literal<["circle"]>
kind
:
import Schema
Schema
.
function Literal<["circle"]>(literals_0: "circle"): Schema.Literal<["circle"]> (+2 overloads)

@since3.10.0

Literal
("circle"),
radius: typeof Schema.Number
radius
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
const
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)

@since3.10.0

Struct
({
kind: Schema.Literal<["square"]>
kind
:
import Schema
Schema
.
function Literal<["square"]>(literals_0: "square"): Schema.Literal<["square"]> (+2 overloads)

@since3.10.0

Literal
("square"),
sideLength: typeof Schema.Number
sideLength
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
const
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)

@since3.10.0

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 sets up the kind property as the discriminant for both Circle and Square schemas. The Shape schema then represents a union of these two types, allowing TypeScript to infer the specific shape based on the kind value.

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 (Initial Simple Union)

For example, let’s say you’ve defined a Shape union as a combination of Circle and Square without any special property:

import {
import Schema
Schema
} from "effect"
const
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)

@since3.10.0

Struct
({
radius: typeof Schema.Number
radius
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
const
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)

@since3.10.0

Struct
({
sideLength: typeof Schema.Number
sideLength
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
const
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)

@since3.10.0

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:

Example (Adding Discriminant Property)

import {
import Schema
Schema
} from "effect"
const
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)

@since3.10.0

Struct
({
radius: typeof Schema.Number
radius
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
const
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)

@since3.10.0

Struct
({
sideLength: typeof Schema.Number
sideLength
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
const
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)

@since3.10.0

Union
(
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.

@since3.10.0

transform
(
const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle
,
// Add a "kind" property with the literal value "circle" to 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)

@since3.10.0

Struct
({ ...
const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle
.
TypeLiteral<{ radius: typeof Number$; }, []>.fields: {
readonly radius: typeof Schema.Number;
}
fields
,
kind: Schema.Literal<["circle"]>
kind
:
import Schema
Schema
.
function Literal<["circle"]>(literals_0: "circle"): Schema.Literal<["circle"]> (+2 overloads)

@since3.10.0

Literal
("circle") }),
{
strict?: true
strict
: true,
// Add the discriminant property to Circle
decode: (fromA: {
readonly radius: number;
}, fromI: {
readonly radius: number;
}) => {
readonly radius: number;
readonly kind: "circle";
}
decode
: (
circle: {
readonly radius: number;
}
circle
) => ({ ...
circle: {
readonly radius: number;
}
circle
,
kind: "circle"
kind
: "circle" as
type const = "circle"
const
}),
// Remove the discriminant property
encode: (toI: {
readonly radius: number;
readonly kind: "circle";
}, toA: {
readonly radius: number;
readonly kind: "circle";
}) => {
readonly radius: number;
}
encode
: ({
kind: "circle"
kind
:
_kind: "circle"
_kind
, ...
rest: {
radius: number;
}
rest
}) =>
rest: {
radius: number;
}
rest
}
),
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.

@since3.10.0

transform
(
const Square: Schema.Struct<{
sideLength: typeof Schema.Number;
}>
Square
,
// Add a "kind" property with the literal value "square" to 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)

@since3.10.0

Struct
({ ...
const Square: Schema.Struct<{
sideLength: typeof Schema.Number;
}>
Square
.
TypeLiteral<{ sideLength: typeof Number$; }, []>.fields: {
readonly sideLength: typeof Schema.Number;
}
fields
,
kind: Schema.Literal<["square"]>
kind
:
import Schema
Schema
.
function Literal<["square"]>(literals_0: "square"): Schema.Literal<["square"]> (+2 overloads)

@since3.10.0

Literal
("square") }),
{
strict?: true
strict
: true,
// Add the discriminant property to Square
decode: (fromA: {
readonly sideLength: number;
}, fromI: {
readonly sideLength: number;
}) => {
readonly sideLength: number;
readonly kind: "square";
}
decode
: (
square: {
readonly sideLength: number;
}
square
) => ({ ...
square: {
readonly sideLength: number;
}
square
,
kind: "square"
kind
: "square" as
type const = "square"
const
}),
// Remove the discriminant property
encode: (toI: {
readonly sideLength: number;
readonly kind: "square";
}, toA: {
readonly sideLength: number;
readonly kind: "square";
}) => {
readonly sideLength: number;
}
encode
: ({
kind: "square"
kind
:
_kind: "square"
_kind
, ...
rest: {
sideLength: number;
}
rest
}) =>
rest: {
sideLength: number;
}
rest
}
)
)
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}, {
readonly radius: number;
} | {
readonly sideLength: number;
}>(schema: Schema.Schema<{
readonly radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}, {
readonly radius: number;
} | {
readonly sideLength: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

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
)({
radius: number
radius
: 10 }))
// Output: { radius: 10, kind: 'circle' }
var console: Console

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

The module exports two specific components:

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

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

Example using the global console:

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

Example using the Console class:

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

@seesource

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

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

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

See util.format() for more information.

@sincev0.1.100

log
(
import Schema
Schema
.
decodeUnknownSync<{
readonly radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}, {
readonly radius: number;
} | {
readonly sideLength: number;
}>(schema: Schema.Schema<{
readonly radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}, {
readonly radius: number;
} | {
readonly sideLength: number;
}, never>, options?: ParseOptions): (u: unknown, overrideOptions?: ParseOptions) => {
readonly radius: number;
readonly kind: "circle";
} | {
readonly sideLength: number;
readonly kind: "square";
}
export decodeUnknownSync

@throwsParseError

@since3.10.0

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
)({
sideLength: number
sideLength
: 10 })
)
// 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:

Example (Using Schema.attachPropertySignature for Less Code)

import {
import Schema
Schema
} from "effect"
const
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)

@since3.10.0

Struct
({
radius: typeof Schema.Number
radius
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
const
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)

@since3.10.0

Struct
({
sideLength: typeof Schema.Number
sideLength
:
import Schema
Schema
.
class Number
export Number

@since3.10.0

Number
})
const
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)

@since3.10.0

Union
(
const Circle: Schema.Struct<{
radius: typeof Schema.Number;
}>
Circle
.
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