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 { Schema } from "effect"
const schema = Schema.Struct({ name: Schema.String,})
// Convert an Effect schema into a Standard Schema V1 object//// ┌─── StandardSchemaV1<{ readonly name: string; }>// ▼const standardSchema = Schema.standardSchemaV1(schema)Sync vs Async Validation
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 { Effect, Schema } from "effect"
// Utility function to display sync and async resultsconst print = <T>(t: T) => t instanceof Promise ? t.then((x) => console.log("Promise", JSON.stringify(x, null, 2))) : console.log("Value", JSON.stringify(t, null, 2))
// Define a synchronous schemaconst sync = Schema.Struct({ name: Schema.String,})
// Generate a Standard Schema V1 objectconst syncStandardSchema = Schema.standardSchemaV1(sync)
// Validate synchronouslyprint(syncStandardSchema["~standard"].validate({ name: null }))/*Output:{ "issues": [ { "path": [ "name" ], "message": "Expected string, actual null" } ]}*/
// Define an asynchronous schema with a transformationconst async = Schema.transformOrFail( sync, Schema.Struct({ name: Schema.NonEmptyString, }), { // Simulate an asynchronous validation delay decode: (x) => Effect.sleep("100 millis").pipe(Effect.as(x)), encode: Effect.succeed, },)
// Generate a Standard Schema V1 objectconst asyncStandardSchema = Schema.standardSchemaV1(async)
// Validate asynchronouslyprint(asyncStandardSchema["~standard"].validate({ name: "" }))/*Output:Promise { "issues": [ { "path": [ "name" ], "message": "Expected a non empty string, actual \"\"" } ]}*/Defects
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 { Effect, Schema } from "effect"
// Define a schema with a defect in the decode functionconst defect = Schema.transformOrFail(Schema.String, Schema.String, { // Simulate an internal failure decode: () => Effect.die("Boom!"), encode: Effect.succeed,})
// Generate a Standard Schema V1 objectconst defectStandardSchema = Schema.standardSchemaV1(defect)
// Validate input, triggering a defectconsole.log(defectStandardSchema["~standard"].validate("a"))/*Output:{ issues: [ { message: 'Error: Boom!' } ] }*/