Skip to content

Schema to Standard Schema

The Schema.standardSchemaV1 API allows you to generate a Standard Schema v1 object from an Effect Schema.

Example (Generating a Standard Schema V1)

import {
import Schema
Schema
} from "effect"
const
const schema: Schema.Struct<{
name: typeof Schema.String;
}>
schema
=
import Schema
Schema
.
function Struct<{
name: typeof Schema.String;
}>(fields: {
name: typeof Schema.String;
}): Schema.Struct<{
name: typeof Schema.String;
}> (+1 overload)

@since3.10.0

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

@since3.10.0

String
})
// Convert an Effect schema into a Standard Schema V1 object
//
// ┌─── StandardSchemaV1<{ readonly name: string; }>
// ▼
const
const standardSchema: StandardSchemaV1<{
readonly name: string;
}, {
readonly name: string;
}>
standardSchema
=
import Schema
Schema
.
const standardSchemaV1: <{
readonly name: string;
}, {
readonly name: string;
}>(schema: Schema.Schema<{
readonly name: string;
}, {
readonly name: string;
}, never>) => StandardSchemaV1<{
readonly name: string;
}, {
readonly name: string;
}>

Returns a "Standard Schema" object conforming to the Standard Schema v1 specification.

This function creates a schema whose validate method attempts to decode and validate the provided input synchronously. If the underlying Schema includes any asynchronous components (e.g., asynchronous message resolutions or checks), then validation will necessarily return a Promise instead.

Any detected defects will be reported via a single issue containing no path.

@example

import { Schema } from "effect"
const schema = Schema.Struct({
name: Schema.String
})
// ┌─── StandardSchemaV1<{ readonly name: string; }>
// ▼
const standardSchema = Schema.standardSchemaV1(schema)

@since3.13.0

standardSchemaV1
(
const schema: Schema.Struct<{
name: typeof Schema.String;
}>
schema
)

The Schema.standardSchemaV1 API creates a schema whose validate method attempts to decode and validate the provided input synchronously. If the underlying Schema includes any asynchronous components (e.g., asynchronous message resolutions or checks), then validation will necessarily return a Promise instead.

Example (Handling Synchronous and Asynchronous Validation)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Schema
Schema
} from "effect"
// Utility function to display sync and async results
const
const print: <T>(t: T) => void | Promise<void>
print
= <
function (type parameter) T in <T>(t: T): void | Promise<void>
T
>(
t: T
t
:
function (type parameter) T in <T>(t: T): void | Promise<void>
T
) =>
t: T
t
instanceof
var Promise: PromiseConstructor

Represents the completion of an asynchronous operation

Promise
?
t: T & Promise<any>
t
.
Promise<any>.then<void, never>(onfulfilled?: ((value: any) => void | PromiseLike<void>) | null | undefined, onrejected?: ((reason: any) => PromiseLike<never>) | null | undefined): Promise<...>

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

@paramonfulfilled The callback to execute when the Promise is resolved.

@paramonrejected The callback to execute when the Promise is rejected.

@returnsA Promise for the completion of which ever callback is executed.

then
((
x: any
x
) =>
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
("Promise",
var JSON: JSON

An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.

JSON
.
JSON.stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string (+1 overload)

Converts a JavaScript value to a JavaScript Object Notation (JSON) string.

@paramvalue A JavaScript value, usually an object or array, to be converted.

@paramreplacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.

@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.

stringify
(
x: any
x
, null, 2)))
:
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
("Value",
var JSON: JSON

An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.

JSON
.
JSON.stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string (+1 overload)

Converts a JavaScript value to a JavaScript Object Notation (JSON) string.

@paramvalue A JavaScript value, usually an object or array, to be converted.

@paramreplacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.

@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.

stringify
(
t: T
t
, null, 2))
// Define a synchronous schema
const
const sync: Schema.Struct<{
name: typeof Schema.String;
}>
sync
=
import Schema
Schema
.
function Struct<{
name: typeof Schema.String;
}>(fields: {
name: typeof Schema.String;
}): Schema.Struct<{
name: typeof Schema.String;
}> (+1 overload)

@since3.10.0

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

@since3.10.0

String
})
// Generate a Standard Schema V1 object
const
const syncStandardSchema: StandardSchemaV1<{
readonly name: string;
}, {
readonly name: string;
}>
syncStandardSchema
=
import Schema
Schema
.
const standardSchemaV1: <{
readonly name: string;
}, {
readonly name: string;
}>(schema: Schema.Schema<{
readonly name: string;
}, {
readonly name: string;
}, never>) => StandardSchemaV1<{
readonly name: string;
}, {
readonly name: string;
}>

Returns a "Standard Schema" object conforming to the Standard Schema v1 specification.

This function creates a schema whose validate method attempts to decode and validate the provided input synchronously. If the underlying Schema includes any asynchronous components (e.g., asynchronous message resolutions or checks), then validation will necessarily return a Promise instead.

Any detected defects will be reported via a single issue containing no path.

@example

import { Schema } from "effect"
const schema = Schema.Struct({
name: Schema.String
})
// ┌─── StandardSchemaV1<{ readonly name: string; }>
// ▼
const standardSchema = Schema.standardSchemaV1(schema)

@since3.13.0

standardSchemaV1
(
const sync: Schema.Struct<{
name: typeof Schema.String;
}>
sync
)
// Validate synchronously
const print: <StandardSchemaV1<Input = unknown, Output = Input>.Result<{
readonly name: string;
}> | Promise<StandardSchemaV1.Result<{
readonly name: string;
}>>>(t: StandardSchemaV1.Result<...> | Promise<...>) => void | Promise<...>
print
(
const syncStandardSchema: StandardSchemaV1<{
readonly name: string;
}, {
readonly name: string;
}>
syncStandardSchema
["~standard"].
StandardSchemaV1<Input = unknown, Output = Input>.Props<{ readonly name: string; }, { readonly name: string; }>.validate: (value: unknown) => StandardSchemaV1<Input = unknown, Output = Input>.Result<{
readonly name: string;
}> | Promise<StandardSchemaV1.Result<{
readonly name: string;
}>>

Validates unknown input values.

validate
({
name: null
name
: null }))
/*
Output:
{
"issues": [
{
"path": [
"name"
],
"message": "Expected string, actual null"
}
]
}
*/
// Define an asynchronous schema with a transformation
const
const async: Schema.transformOrFail<Schema.Struct<{
name: typeof Schema.String;
}>, Schema.Struct<{
name: typeof Schema.NonEmptyString;
}>, never>
async
=
import Schema
Schema
.
const transformOrFail: <Schema.Struct<{
name: typeof Schema.NonEmptyString;
}>, Schema.Struct<{
name: typeof Schema.String;
}>, never, never>(from: Schema.Struct<{
name: typeof Schema.String;
}>, to: Schema.Struct<...>, options: {
...;
} | {
...;
}) => Schema.transformOrFail<...> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided decoding functions.

@since3.10.0

transformOrFail
(
const sync: Schema.Struct<{
name: typeof Schema.String;
}>
sync
,
import Schema
Schema
.
function Struct<{
name: typeof Schema.NonEmptyString;
}>(fields: {
name: typeof Schema.NonEmptyString;
}): Schema.Struct<{
name: typeof Schema.NonEmptyString;
}> (+1 overload)

@since3.10.0

Struct
({
name: typeof Schema.NonEmptyString
name
:
import Schema
Schema
.
class NonEmptyString

@since3.10.0

NonEmptyString
}),
{
// Simulate an asynchronous validation delay
decode: (x: {
readonly name: string;
}) => Effect.Effect<{
readonly name: string;
}, never, never>
decode
: (
x: {
readonly name: string;
}
x
) =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const sleep: (duration: DurationInput) => Effect.Effect<void>

Suspends the execution of an effect for a specified Duration.

Details

This function pauses the execution of an effect for a given duration. It is asynchronous, meaning that it does not block the fiber executing the effect. Instead, the fiber is suspended during the delay period and can resume once the specified time has passed.

The duration can be specified using various formats supported by the Duration module, such as a string ("2 seconds") or numeric value representing milliseconds.

@example

import { Effect } from "effect"
const program = Effect.gen(function*() {
console.log("Starting task...")
yield* Effect.sleep("3 seconds") // Waits for 3 seconds
console.log("Task completed!")
})
// Effect.runFork(program)
// Output:
// Starting task...
// Task completed!

@since2.0.0

sleep
("100 millis").
Pipeable.pipe<Effect.Effect<void, never, never>, Effect.Effect<{
readonly name: string;
}, never, never>>(this: Effect.Effect<...>, ab: (_: Effect.Effect<void, never, never>) => Effect.Effect<{
readonly name: string;
}, never, never>): Effect.Effect<...> (+21 overloads)
pipe
(
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const as: <{
readonly name: string;
}>(value: {
readonly name: string;
}) => <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<{
readonly name: string;
}, E, R> (+1 overload)

Replaces the value inside an effect with a constant value.

Details

This function allows you to ignore the original value inside an effect and replace it with a constant value.

When to Use

It is useful when you no longer need the value produced by an effect but want to ensure that the effect completes successfully with a specific constant result instead. For instance, you can replace the value produced by a computation with a predefined value, ignoring what was calculated before.

@example

// Title: Replacing a Value
import { pipe, Effect } from "effect"
// Replaces the value 5 with the constant "new value"
const program = pipe(Effect.succeed(5), Effect.as("new value"))
// Effect.runPromise(program).then(console.log)
// Output: "new value"

@since2.0.0

as
(
x: {
readonly name: string;
}
x
)),
encode: <A>(value: A) => Effect.Effect<A>
encode
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <A>(value: A) => Effect.Effect<A>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
}
)
// Generate a Standard Schema V1 object
const
const asyncStandardSchema: StandardSchemaV1<{
readonly name: string;
}, {
readonly name: string;
}>
asyncStandardSchema
=
import Schema
Schema
.
const standardSchemaV1: <{
readonly name: string;
}, {
readonly name: string;
}>(schema: Schema.Schema<{
readonly name: string;
}, {
readonly name: string;
}, never>) => StandardSchemaV1<{
readonly name: string;
}, {
readonly name: string;
}>

Returns a "Standard Schema" object conforming to the Standard Schema v1 specification.

This function creates a schema whose validate method attempts to decode and validate the provided input synchronously. If the underlying Schema includes any asynchronous components (e.g., asynchronous message resolutions or checks), then validation will necessarily return a Promise instead.

Any detected defects will be reported via a single issue containing no path.

@example

import { Schema } from "effect"
const schema = Schema.Struct({
name: Schema.String
})
// ┌─── StandardSchemaV1<{ readonly name: string; }>
// ▼
const standardSchema = Schema.standardSchemaV1(schema)

@since3.13.0

standardSchemaV1
(
const async: Schema.transformOrFail<Schema.Struct<{
name: typeof Schema.String;
}>, Schema.Struct<{
name: typeof Schema.NonEmptyString;
}>, never>
async
)
// Validate asynchronously
const print: <StandardSchemaV1<Input = unknown, Output = Input>.Result<{
readonly name: string;
}> | Promise<StandardSchemaV1.Result<{
readonly name: string;
}>>>(t: StandardSchemaV1.Result<...> | Promise<...>) => void | Promise<...>
print
(
const asyncStandardSchema: StandardSchemaV1<{
readonly name: string;
}, {
readonly name: string;
}>
asyncStandardSchema
["~standard"].
StandardSchemaV1<Input = unknown, Output = Input>.Props<{ readonly name: string; }, { readonly name: string; }>.validate: (value: unknown) => StandardSchemaV1<Input = unknown, Output = Input>.Result<{
readonly name: string;
}> | Promise<StandardSchemaV1.Result<{
readonly name: string;
}>>

Validates unknown input values.

validate
({
name: string
name
: "" }))
/*
Output:
Promise {
"issues": [
{
"path": [
"name"
],
"message": "Expected a non empty string, actual \"\""
}
]
}
*/

If an unexpected defect occurs during validation, it is reported as a single issue without a path. This ensures that unexpected errors do not disrupt schema validation but are still captured and reported.

Example (Handling Defects)

import {
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
,
import Schema
Schema
} from "effect"
// Define a schema with a defect in the decode function
const
const defect: Schema.transformOrFail<typeof Schema.String, typeof Schema.String, never>
defect
=
import Schema
Schema
.
const transformOrFail: <typeof Schema.String, typeof Schema.String, never, never>(from: typeof Schema.String, to: typeof Schema.String, options: {
readonly decode: (fromA: string, options: ParseOptions, ast: Transformation, fromI: string) => Effect.Effect<...>;
readonly encode: (toI: string, options: ParseOptions, ast: Transformation, toA: string) => Effect.Effect<...>;
readonly strict?: true;
} | {
...;
}) => Schema.transformOrFail<...> (+1 overload)

Create a new Schema by transforming the input and output of an existing Schema using the provided decoding functions.

@since3.10.0

transformOrFail
(
import Schema
Schema
.
class String
export String

@since3.10.0

String
,
import Schema
Schema
.
class String
export String

@since3.10.0

String
, {
// Simulate an internal failure
decode: () => Effect.Effect<never, never, never>
decode
: () =>
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const die: (defect: unknown) => Effect.Effect<never>

Creates an effect that terminates a fiber with a specified error.

Details

This function is used to signal a defect, which represents a critical and unexpected error in the code. When invoked, it produces an effect that does not handle the error and instead terminates the fiber.

The error channel of the resulting effect is of type never, indicating that it cannot recover from this failure.

When to Use

Use this function when encountering unexpected conditions in your code that should not be handled as regular errors but instead represent unrecoverable defects.

@seedieSync for a variant that throws a specified error, evaluated lazily.

@seedieMessage for a variant that throws a RuntimeException with a message.

@example

// Title: Terminating on Division by Zero with a Specified Error
import { Effect } from "effect"
const divide = (a: number, b: number) =>
b === 0
? Effect.die(new Error("Cannot divide by zero"))
: Effect.succeed(a / b)
// ┌─── Effect<number, never, never>
// ▼
const program = divide(1, 0)
// Effect.runPromise(program).catch(console.error)
// Output:
// (FiberFailure) Error: Cannot divide by zero
// ...stack trace...

@since2.0.0

die
("Boom!"),
encode: <A>(value: A) => Effect.Effect<A>
encode
:
import Effect

@since2.0.0

@since2.0.0

@since2.0.0

Effect
.
const succeed: <A>(value: A) => Effect.Effect<A>

Creates an Effect that always succeeds with a given value.

When to Use

Use this function when you need an effect that completes successfully with a specific value without any errors or external dependencies.

@seefail to create an effect that represents a failure.

@example

// Title: Creating a Successful Effect
import { Effect } from "effect"
// Creating an effect that represents a successful scenario
//
// ┌─── Effect<number, never, never>
// ▼
const success = Effect.succeed(42)

@since2.0.0

succeed
})
// Generate a Standard Schema V1 object
const
const defectStandardSchema: StandardSchemaV1<string, string>
defectStandardSchema
=
import Schema
Schema
.
const standardSchemaV1: <string, string>(schema: Schema.Schema<string, string, never>) => StandardSchemaV1<string, string>

Returns a "Standard Schema" object conforming to the Standard Schema v1 specification.

This function creates a schema whose validate method attempts to decode and validate the provided input synchronously. If the underlying Schema includes any asynchronous components (e.g., asynchronous message resolutions or checks), then validation will necessarily return a Promise instead.

Any detected defects will be reported via a single issue containing no path.

@example

import { Schema } from "effect"
const schema = Schema.Struct({
name: Schema.String
})
// ┌─── StandardSchemaV1<{ readonly name: string; }>
// ▼
const standardSchema = Schema.standardSchemaV1(schema)

@since3.13.0

standardSchemaV1
(
const defect: Schema.transformOrFail<typeof Schema.String, typeof Schema.String, never>
defect
)
// Validate input, triggering a defect
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
(
const defectStandardSchema: StandardSchemaV1<string, string>
defectStandardSchema
["~standard"].
StandardSchemaV1<Input = unknown, Output = Input>.Props<string, string>.validate: (value: unknown) => StandardSchemaV1<Input = unknown, Output = Input>.Result<string> | Promise<StandardSchemaV1.Result<string>>

Validates unknown input values.

validate
("a"))
/*
Output:
{ issues: [ { message: 'Error: Boom!' } ] }
*/