Skip to content
Effect 4.0 is here. One ecosystem. Zero dependencies.

Schema

Describes data shapes and how unknown input becomes trusted values.

A schema can validate input, decode it into an application type, and encode that value back to another representation. This module contains the main schema, codec, decoder, and encoder APIs, together with schemas for common JavaScript values and Effect data types. It also supports refinements, transformations, defaults, classes, JSON Schema generation, test data generation, formatting, equivalence, optics, and differs derived from schema definitions.

639 exports Since v3.10.0 Source

Annotations

Since v4.0.0

Adds metadata annotations to a schema without changing its runtime behavior. This is the pipeable (curried) counterpart of the .annotate method.

Details

Annotations provide extra context used by documentation generators, JSON Schema converters, error formatters, and other tooling. Common keys include title, description, examples, message, and identifier.

See

Signature

declare function annotate<S extends Top>(annotations: Bottom<S["Type"], S["~type.parameters"]>): (self: S) => S["Rebuild"]

Example Adding a title and description

import { Schema } from "effect"
const Age = Schema.Natural.pipe(
Schema.annotate({
title: "Age",
description: "A non-negative integer representing age in years"
})
)
Schema.resolveAnnotations(Age)?.title // => "Age"

Adds metadata annotations to the encoded side of a schema without changing its runtime behavior. This is the encoded-side counterpart of annotate, which targets the decoded (Type) side.

Details

Internally the schema is flipped so that Encoded becomes Type, annotated, and then flipped back.

See

  • annotate to annotate the type side instead.

Signature

declare function annotateEncoded<S extends Top>(annotations: Bottom<S["Encoded"], readonly []>): (self: S) => S["Rebuild"]

Example Adding a title to the encoded representation

import { Schema } from "effect"
const schema = Schema.NumberFromString.pipe(
Schema.annotateEncoded({
title: "my title"
})
)
Schema.toEncoded(schema).ast.annotations?.title // => "my title"

Adds key-level annotations to a schema field. This is the pipeable (curried) counterpart of the .annotateKey method.

Details

Key annotations apply to a field's position inside a Struct or Tuple rather than to the field's value type. They can carry a messageMissingKey to customise the error shown when the field is absent, as well as standard documentation fields such as title, description, and examples.

Signature

declare function annotateKey<S extends Top>(annotations: Key<S["Type"]>): (self: S) => S["Rebuild"]

Example Customizing the missing-key message for a required field

import { Schema } from "effect"
const schema = Schema.Struct({
username: Schema.String.pipe(
Schema.annotateKey({
description: "The username used to log in",
messageMissingKey: "Username is required"
})
)
})
schema.fields.username.ast.context?.annotations?.messageMissingKey // => "Username is required"

Branding

Since v3.10.0

Intersects a schema's output type with Brand.Brand<B> to prevent accidental mixing of structurally identical types.

When to use

Use to make values decoded by an existing schema nominally distinct when the schema already carries the runtime validation you need.

Gotchas

  • identifier must be a single concrete string literal. Widened strings, unions, and open template literal types are rejected.
  • brand only narrows the TypeScript output type. It does not change the schema's runtime AST or add runtime checks.
  • Schema representations and generated schema code omit the brand. Reapply brand after rebuilding or generating a schema when the nominal type is still required.

See

  • fromBrand for applying a Brand constructor's checks along with its branded type

Signature

declare function brand<B extends string>(identifier: B & EnsureSingleBrandKey<B>): <S extends ConstraintRebuildable>(schema: S) => brand<S["Rebuild"], B>

brand

interface
Since v3.10.0

Type-level representation returned by brand.

Signature

interface brand<S extends Constraint, B extends string> extends BottomLazy<S["ast"], brand<S, B>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["Type"] & Brand<B>;
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly identifier: string;
readonly Iso: S["Type"] & Brand<B>;
readonly schema: S;
readonly Type: S["Type"] & Brand<B>;
}
Since v3.10.0

Creates a branded schema from a Brand.Constructor, applying the constructor's checks and branded type to the underlying schema.

When to use

Use to reuse the checks from a constructor with one concrete brand key.

Gotchas

identifier must match the constructor's only brand key. Apply fromBrand repeatedly to compose distinct brands, and use Union to represent alternatives.

See

  • brand for adding a brand without constructor checks

Signature

declare function fromBrand<A extends Brand<any>>(identifier: keyof A["~effect/Brand"] & string, ctor: Constructor<A> & EnsureSingleBrandKey<FromBrandKeys<A>>): <S extends Top & {
readonly Type: Unbranded<A>;
}>(self: S) => brand<S["Rebuild"], B>

Combinators

Adds fields to a struct schema through a struct-mapping lambda.

When to use

Use to add the same fields to an existing struct or every struct member of a union.

Details

This is a shortcut for MyStruct.mapFields(Struct.assign(fields)).

Signature

declare function fieldsAssign<NewFields extends Fields>(fields: NewFields): fieldsAssign<NewFields>

Example Adding fields to a union of structs

import { Schema, Tuple } from "effect"
// Add a new field to all members of a union of structs
const schema = Schema.Union([
Schema.Struct({ a: Schema.String }),
Schema.Struct({ b: Schema.Number })
]).mapMembers(Tuple.map(Schema.fieldsAssign({ c: Schema.Number })))
Schema.decodeSync(schema)({ a: "a", c: 1 }) // => { a: "a", c: 1 }

Makes a struct field mutable (removes the readonly modifier on the property). Use readonlyKey to reverse.

Signature

declare const mutableKey: mutableKeyLambda
Since v3.10.0

Marks a struct field as optional, allowing the key to be absent or undefined.

Details

The resulting property may be absent or explicitly set to undefined. Equivalent to optionalKey(UndefinedOr(S)).

Use optionalKey instead if you want exact optional semantics (absent only, not undefined).

Signature

declare const optional: optionalLambda

Example Defining an optional field accepting undefined

import { Schema } from "effect"
const schema = Schema.Struct({
name: Schema.String,
age: Schema.optional(Schema.Number)
})
// { readonly name: string; readonly age?: number | undefined }
type Person = typeof schema.Type

Creates an exact optional key schema for struct fields. Unlike optional, this creates exact optional properties (not | undefined) that can be completely omitted from the object.

Signature

declare const optionalKey: optionalKeyLambda

Example Creating a struct with optional key

import { Schema } from "effect"
const schema = Schema.Struct({
name: Schema.String,
age: Schema.optionalKey(Schema.Number)
})
// Type: { readonly name: string; readonly age?: number }
type Person = typeof schema["Type"]

Reverses mutableKey and returns the inner readonly schema.

When to use

Use to remove mutable-key wrapping from a schema field that was previously wrapped with mutableKey.

Signature

declare const readonlyKey: readonlyKeyLambda
Since v3.10.0

Reverses optional and returns the inner schema.

When to use

Use to remove optional wrapping from a schema field that was previously wrapped with optional.

Details

This also unwraps the UndefinedOr member added by optional.

Signature

declare const required: requiredLambda

Reverses optionalKey and returns the inner required schema.

When to use

Use to remove optional-key wrapping from a schema field that was previously wrapped with optionalKey.

Signature

declare const requiredKey: requiredKeyLambda

Augments an existing Union of tagged structs with utility methods and an ordered tuple of discriminant values.

Gotchas

Throws if multiple members use the same discriminant property key.

See

  • TaggedUnion for a shorthand that builds the union from scratch

Signature

declare function toTaggedUnion<Tag extends PropertyKey>(tag: Tag): <Members extends readonly Array<Constraint & {
readonly Type: { [K in PropertyKey]: PropertyKey };
}>>(self: Union<Members>) => toTaggedUnion<Tag, Members>

Example Adding tagged-union utilities to an existing union

import { Schema } from "effect"
const A = Schema.TaggedStruct("A", { value: Schema.Number })
const B = Schema.TaggedStruct("B", { name: Schema.String })
const MyUnion = Schema.Union([A, B]).pipe(Schema.toTaggedUnion("_tag"))
// Pattern-match on the union
const result = MyUnion.match({ _tag: "A", value: 1 }, {
A: (a) => `number: ${a.value}`,
B: (b) => `name: ${b.name}`
})
result // => "number: 1"
Since v4.0.0

Type-level representation returned by toTaggedUnion.

Signature

type toTaggedUnion<Tag extends PropertyKey, Members extends ReadonlyArray<Constraint & {
readonly Type: { [K in Tag]: PropertyKey };
}>> = Union<Members> & TaggedUnionUtils<Tag, Members>

Constructors

Since v4.0.0

Signature

declare const Array: ArrayLambda

Creates a schema that accepts either a value decoded by schema or an array decoded by Schema.Array(schema), then returns an array.

When to use

Use to accept input that may be provided either as one item or as an array, while normalizing decoded values to a readonly array.

Details

During encoding, one-element arrays are encoded as the single element. Empty arrays and arrays with two or more elements are encoded as arrays.

Gotchas

The single-value branch is tried before the array branch. If schema itself accepts arrays, an array input can be treated as one value and wrapped in a one-element array.

See

  • Array for accepting only array input
  • NonEmptyArray for requiring at least one decoded element

Signature

declare function ArrayEnsure<S extends Constraint>(schema: S): ArrayEnsure<S>

ArrayEnsure

interface
Since v3.10.0

Type-level representation returned by ArrayEnsure.

Signature

interface ArrayEnsure<S extends Constraint> extends decodeTo<$Array<toType<S>>, Union<readonly [S, $Array<S>]>> {
constructor(_: never);
readonly Rebuild: ArrayEnsure<S>;
}
Since v3.10.0

Creates a schema-backed class whose constructor validates input against a Struct schema. Construction throws an Error with a SchemaIssue.Issue in its cause on invalid input.

When to use

Use when you need a schema-backed data class with validated construction, schema-derived decoding/encoding, and class-style methods or inheritance.

Details

Pass the desired class type as the first type parameter. The second optional type parameter can be used to add nominal brands.

The identifier is the schema's stable runtime name. It is exposed on the class, stored in the schema AST, and used to label diagnostics and generated references as well as to format class instances.

It also derives a runtime marker that recognizes instances across hot module reloads, where instanceof can fail because the constructor has been replaced. The identifier is explicit because the outer JavaScript class name is not available while the extends expression is evaluated and may change through renaming or minification.

Gotchas

Passing disableChecks in the options skips constructor validation.

See

  • TaggedClass for adding a _tag literal field to the class schema
  • Error for defining schema-backed error classes
  • TaggedError for defining tagged schema-backed error classes

Signature

declare const Class: <Self = never, Brand = {}>(identifier: string) => {
<Fields extends Fields>(fields: Fields, annotations?: Declaration<Self, readonly [Struct<Fields>]>): [Self] extends [never] ? "Missing `Self` generic - use `class Self extends Schema.Class<Self>(...)`" : Class<Self, Struct<Fields>, Brand>;
<S extends Struct<Fields>>(schema: S, annotations?: Declaration<Self, readonly [S]>): [Self] extends [never] ? "Missing `Self` generic - use `class Self extends Schema.Class<Self>(...)`" : Class<Self, S, Brand>;
}

Example Defining a basic class

import { Schema } from "effect"
class Person extends Schema.Class<Person>("Person")({
name: Schema.String,
age: Schema.Number
}) {}
const alice = new Person({ name: "Alice", age: 30 })
alice.name // => "Alice"
String(alice) // => "Person({\"name\":\"Alice\",\"age\":30})"

Example Extending a class

import { Schema } from "effect"
class Animal extends Schema.Class<Animal>("Animal")({
name: Schema.String
}) {}
class Dog extends Animal.extend<Dog>("Dog")({
breed: Schema.String
}) {}
const dog = new Dog({ name: "Rex", breed: "Labrador" })
dog.name // => "Rex"
dog.breed // => "Labrador"
Since v3.10.0

Creates a schema for a non-parametric opaque type using a type-guard function. The schema accepts any unknown value and succeeds when is returns true, failing with an InvalidType issue otherwise.

When to use

Use when you are defining a schema for an opaque type with no type parameters and validation can be expressed as a type guard.

See

Signature

declare function declare<T, Iso = T>(is: (u: unknown) => u is T, annotations?: Declaration<T, readonly []>): declare<T, Iso>

Example

import { Schema } from "effect"
type UserId = string & { readonly _tag: "UserId" }
const isUserId = (u: unknown): u is UserId =>
typeof u === "string" && u.startsWith("user_")
const UserId = Schema.declare<UserId>(isUserId, {
title: "UserId",
description: "A user identifier starting with 'user_'"
})
Schema.decodeUnknownSync(UserId)("user_123") // => "user_123"

declare

interface
Since v3.13.3

Type-level representation returned by declare.

Signature

interface declare<T, Iso = T> extends declareConstructor<T, T, readonly [], Iso> {
constructor(_: never);
readonly Rebuild: declare<T, Iso>;
}

Creates a schema for a parametric type (a generic container such as Array<A>, Option<A>, etc.) by accepting a list of type-parameter schemas and a decoder factory.

When to use

Use when you are defining a schema for a generic container whose validation depends on one or more type-parameter schemas.

Details

The outer call declareConstructor<T, E, Iso>() fixes the decoded type T, the encoded type E, and the optional iso type. The inner call receives:

  • typeParameters โ€” the concrete schemas for each type variable
  • run โ€” a factory that, given resolved codecs for each type parameter, returns a parsing function (u, ast, options) => Effect<T, Issue>
  • annotations โ€” optional metadata

See

  • declare for creating schemas for non-parametric types.

Signature

declare function declareConstructor<T, E = T, Iso = T>(): <TypeParameters extends readonly Array<Constraint>>(typeParameters: TypeParameters, run: (typeParameters: { [K in string | number | symbol]: Codec<TypeParameters[K]["Type"], TypeParameters[K]["Encoded"], never, never> }) => (u: unknown, self: Declaration, options: ParseOptions) => Effect<T, Issue>, annotations?: Declaration<T, TypeParameters>) => declareConstructor<T, E, TypeParameters, Iso>
Since v4.0.0

Type-level representation returned by declareConstructor.

Signature

interface declareConstructor<T, E, TypeParameters extends ReadonlyArray<Constraint>, Iso = T> extends Bottom<T, E, TypeParameters[number]["DecodingServices"], TypeParameters[number]["EncodingServices"], SchemaAST.Declaration, declareConstructor<T, E, TypeParameters, Iso>, T, Iso, TypeParameters> {
constructor(_: never);
}
Since v4.0.0

Creates a schema from a TypeScript enum object. Validates that the input is one of the enum's values. Numeric enum values must be finite.

Gotchas

Throws when a numeric member is NaN, Infinity, or -Infinity.

Signature

declare function Enum<A extends {
[x: string]: string | number;
}>(enums: A): Enum<A>

Example Defining a direction enum

import { Schema } from "effect"
enum Direction {
Up = "Up",
Down = "Down"
}
const schema = Schema.Enum(Direction)
Schema.decodeSync(schema)(Direction.Up) // => "Up"
Since v4.0.0

Creates a schema-backed error class that can be used as a typed, yieldable error in Effect programs. Combines Class validation with the YieldableError interface so instances can be yielded directly inside Effect.gen.

Signature

declare const Error: <Self = never, Brand = {}>(identifier: string) => {
<Fields extends Fields>(fields: Fields, annotations?: Declaration<Self, readonly [Struct<Fields>]>): [Self] extends [never] ? "Missing `Self` generic - use `class Self extends Schema.Error<Self>(...)`" : Class<Self, Struct<Fields>, YieldableError & Brand>;
<S extends Struct<Fields>>(schema: S, annotations?: Declaration<Self, readonly [S]>): [Self] extends [never] ? "Missing `Self` generic - use `class Self extends Schema.Error<Self>(...)`" : Class<Self, S, YieldableError & Brand>;
}

Example Schema-backed error

import { Effect, Schema } from "effect"
class NotFound extends Schema.Error<NotFound>("NotFound")({
id: Schema.Number
}) {}
const program = Effect.gen(function*() {
yield* new NotFound({ id: 1 })
})
const error = await Effect.runPromise(Effect.flip(program))
error.id // => 1

Creates a schema that validates values using instanceof. Decoding and encoding pass the value through unchanged.

Signature

declare function instanceOf<C extends (...args: any) => any, Iso = InstanceType<C>>(constructor: C, annotations?: Declaration<InstanceType<C>, readonly []>): instanceOf<InstanceType<C>, Iso>

Example Defining a schema for a built-in class

import { Schema } from "effect"
const DateSchema = Schema.instanceOf(Date)
const decoded = Schema.decodeUnknownSync(DateSchema)(new Date("2024-01-01"))
decoded.toISOString() // => "2024-01-01T00:00:00.000Z"
Since v3.10.0

Creates a schema for a single literal value (string, number, bigint, boolean, or null).

See

  • Literals for a schema that represents a union of literals.
  • tag for a schema that represents a literal value that can be used as a discriminator field in tagged unions and has a constructor default.

Signature

declare function Literal<L extends LiteralValue>(literal: L): Literal<L>

Example Defining a string literal

import { Schema } from "effect"
const schema = Schema.Literal("hello")
// Type: Schema.Literal<"hello">
Schema.decodeSync(schema)("hello") // => "hello"
Since v4.0.0

Creates a union schema from an array of literal values.

See

  • Literal for a schema that represents a single literal.

Signature

declare function Literals<L extends readonly Array<LiteralValue>>(literals: L): Literals<L>

Example Defining status codes

import { Schema } from "effect"
const schema = Schema.Literals(["active", "inactive", "pending"])
Schema.decodeSync(schema)("active") // => "active"
Since v3.10.0

Creates a schema from an AST (Abstract Syntax Tree) node.

Details

This is the fundamental constructor for all schemas in the Effect Schema library. It takes an AST node and wraps it in a fully-typed schema that preserves all type information and provides the complete schema API.

The make function is used internally to create all primitive schemas like String, Number, Boolean, etc., as well as more complex schemas. It's the bridge between the untyped AST representation and the strongly-typed schema.

Signature

declare const make: <S extends Constraint>(ast: S["ast"], options?: object) => S

Creates a custom validation filter from a predicate function.

Details

The predicate receives the decoded input value, the schema AST, and parse options, and returns a FilterOutput. Non-success outputs are normalized into schema issues. The annotations parameter annotates the filter itself; with the default formatter, failures use message first, expected second, and <filter> when neither is provided.

When abort is true, parsing stops after this filter fails instead of collecting later check failures.

Signature

declare const makeFilter: <T>(filter: (input: T, ast: SchemaAST.AST, options: SchemaAST.ParseOptions) => FilterOutput, annotations?: Annotations.Filter, abort?: boolean) => SchemaAST.Filter<T>

Example Reporting failure at a nested path

import { Result, Schema } from "effect"
const schema = Schema.Struct({ password: Schema.String, confirmPassword: Schema.String }).check(
Schema.makeFilter((o) =>
o.password === o.confirmPassword
? undefined
: { path: ["password"], issue: "password and confirmPassword must match" }
)
)
const result = Schema.decodeUnknownResult(schema)({ password: "123456", confirmPassword: "1234567" })
if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Pointer") {
result.failure.issue.issue.path // => ["password"]
}

Example Reporting multiple failures at once

import { Result, Schema } from "effect"
const schema = Schema.Struct({ a: Schema.Finite, b: Schema.Finite, c: Schema.Finite }).check(
Schema.makeFilter((o) => {
const issues: Array<Schema.FilterIssue> = []
if (o.a > 0) {
if (o.b <= 0) issues.push({ path: ["b"], issue: "b must be greater than 0" })
if (o.c <= 0) issues.push({ path: ["c"], issue: "c must be greater than 0" })
}
return issues
})
)
const result = Schema.decodeUnknownResult(schema)({ a: 1, b: 0, c: 0 })
if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Composite") {
result.failure.issue.issue.issues.map((issue) => issue._tag === "Pointer" ? issue.path : []) // => [["b"], ["c"]]
}

Groups multiple checks into a single SchemaAST.FilterGroup, applying optional shared annotations to the group as a whole.

Signature

declare function makeFilterGroup<T>(checks: readonly [Check<T>, Check<T>], annotations: Filter | undefined): FilterGroup<T>

Defines a non-empty ReadonlyArray schema โ€” at least one element required. Type is readonly [T, ...T[]].

Signature

declare const NonEmptyArray: NonEmptyArrayLambda

Example Defining a non-empty array of numbers

import { Schema } from "effect"
const schema = Schema.NonEmptyArray(Schema.Number)
Schema.decodeUnknownSync(schema)([1, 2, 3]) // => [1, 2, 3]
Since v3.10.0

Creates a union schema of S | null | undefined.

Signature

declare const NullishOr: NullishOrLambda
Since v3.10.0

Creates a union schema of S | null.

Signature

declare const NullOr: NullOrLambda
Since v4.0.0

Wraps a struct schema so that its decoded Type becomes a nominally distinct type Self. Useful for creating opaque types that are structurally identical to a base struct but type-incompatible with it.

Signature

declare function Opaque<Self, Brand = {}>(): <S extends Top>(schema: S) => Opaque<Self, S, Brand> & Omit<S, keyof Top>

Example Defining opaque structs

import { Schema } from "effect"
class Person extends Schema.Opaque<Person>()(
Schema.Struct({
name: Schema.String
})
) {}
// Decoded value is Person, not { name: string }
const person = Schema.decodeUnknownSync(Person)({ name: "Alice" })
person.name // => "Alice"
Since v3.10.0

Defines a record schema whose dynamic properties are selected by a key schema and decoded with a value schema.

Details

For dynamic keys, the key schema selects matching own properties and the value schema decodes or encodes only those selected properties. Checks on string, number, symbol, and template literal key schemas narrow which properties are selected.

For transformed key schemas, property selection is based on encoded property names before the selected key is decoded.

Gotchas

When decoded or encoded key transformations produce the same property key, sequential parsing applies selected own properties in selection order, so the later selected property overwrites the earlier value. Dynamic key selection always examines own properties. Finite literal keys are declared fields and may therefore be inherited. Output key order is not guaranteed.

Signature

declare function Record<Key extends Key, Value extends Constraint>(key: Key, value: Value): $Record<Key, Value>

Example Defining a string-keyed record of numbers

import { Schema } from "effect"
const schema = Schema.Record(Schema.String, Schema.Number)
// { readonly [x: string]: number }
type R = typeof schema.Type
Schema.decodeUnknownSync(schema)({ a: 1, b: 2 }) // => { a: 1, b: 2 }
Since v3.10.0

Defines a struct schema from a map of field schemas.

Details

Each field value is a schema. Use optionalKey or optional to mark fields as optional, and mutableKey to mark them as mutable.

The resulting schema's Type is a readonly object type with the fields' decoded types. The Encoded form mirrors the field schemas' encoded types. Declared fields may be inherited and are copied to own properties in the output. The __proto__ field is accepted only when it is an own property. Parsing does not guarantee that output keys retain their input order.

Signature

declare function Struct<Fields extends Fields>(fields: Fields): Struct<Fields>

Example Defining a basic struct

import { Schema } from "effect"
const Person = Schema.Struct({
name: Schema.String,
age: Schema.Number,
email: Schema.optionalKey(Schema.String)
})
// { readonly name: string; readonly age: number; readonly email?: string }
type Person = typeof Person.Type
Schema.decodeUnknownSync(Person)({ name: "Alice", age: 30 }) // => { name: "Alice", age: 30 }

Extends a struct schema with one or more record (index-signature) schemas, producing a schema whose decoded type intersects the struct and all records.

Gotchas

The base schema must have an object-shaped encoded type. Whole-object transformations are not supported, even with an empty rest array. Apply transformations such as Schema.fromJsonString to the completed StructWithRest schema instead. Object-shaped encoded types alone do not guarantee compatibility: unsupported encodings are still rejected at runtime. Transformations on individual fields remain supported.

TypeScript index signatures also apply to fixed keys. StructWithRest does not reject incompatible fixed fields at the call site; use StructWithRest.ValidateRecords when you want an explicit type-level compatibility check.

Signature

declare function StructWithRest<S extends Objects, Records extends Records>(schema: S, records: Records): StructWithRest<S, Records>

Example Defining structs with string-indexed extra keys

import { Schema } from "effect"
const schema = Schema.StructWithRest(
Schema.Struct({ id: Schema.Number }),
[Schema.Record(Schema.String, Schema.Number)]
)
// { readonly id: number, readonly [x: string]: number }
type T = typeof schema.Type
Since v3.10.0

Creates a suspended schema that defers evaluation until needed. This is essential for creating recursive schemas where a schema references itself, preventing infinite recursion during schema definition.

Signature

declare function suspend<S extends Constraint>(f: () => S): suspend<S>

Example Defining recursive tree schemas

import { Schema } from "effect"
interface Tree {
readonly value: number
readonly children: ReadonlyArray<Tree>
}
const Tree = Schema.Struct({
value: Schema.Number,
children: Schema.Array(Schema.suspend((): Schema.Codec<Tree> => Tree))
})
Schema.decodeSync(Tree)({ value: 1, children: [] }) // => { value: 1, children: [] }
Since v3.10.0

Combines a Literal schema with withConstructorDefault, making it ideal for discriminator fields in tagged unions. When constructing via make, the _tag field can be omitted and will be filled automatically.

See

Signature

declare function tag<Tag extends LiteralValue>(literal: Tag): tag<Tag>

Example Defining a discriminated union tag

import { Schema } from "effect"
const A = Schema.Struct({ _tag: Schema.tag("A"), value: Schema.Number })
// _tag is optional in make, auto-filled to "A"
const a = A.make({ value: 42 })
a // => { _tag: "A", value: 42 }

tag

interface
Since v3.10.0

Type-level representation returned by tag.

Signature

interface tag<Tag extends SchemaAST.LiteralValue> extends withConstructorDefault<Literal<Tag>> {
constructor(_: never);
}

Creates a literal _tag schema that is omitted from encoded output.

When to use

Use to decode data that omits the discriminator field while still constructing values with a _tag for tagged union matching.

Details

The tag is filled during decoding and construction, like tag, but is omitted when encoding.

See

  • tag for the variant that keeps the tag during encoding

Signature

declare function tagDefaultOmit<Tag extends LiteralValue>(literal: Tag): withDecodingDefaultKey<tag<Tag>, never>

Example Omitting tags during encoding

import { Schema } from "effect"
const A = Schema.Struct({
_tag: Schema.tagDefaultOmit("A"),
value: Schema.Number
})
// Encode strips the _tag field
Schema.encodeUnknownSync(A)({ _tag: "A", value: 1 }) // => { value: 1 }

Defines a schema-backed class with an automatically populated _tag field.

When to use

Use to define class instances that are validated by a schema and participate in tagged union matching.

Details

The optional identifier parameter overrides the schema identifier; it defaults to the tag value.

Signature

declare const TaggedClass: <Self = never, Brand = {}>(identifier?: string) => {
<Tag extends string, Fields extends Fields>(tag: Tag, fields: Fields, annotations?: Declaration<Self, readonly [TaggedStruct<Tag, Fields>]>): [Self] extends [never] ? "Missing `Self` generic - use `class Self extends Schema.TaggedClass<Self>(...)`" : Class<Self, TaggedStruct<Tag, Fields>, Brand>;
<Tag extends string, S extends Struct<Fields>>(tag: Tag, schema: S, annotations?: Declaration<Self, readonly [Struct<{ [K in string | number | symbol]: {
readonly _tag: tag<...>;
} & S["fields"][K] }>]>): [Self] extends [never] ? "Missing `Self` generic - use `class Self extends Schema.TaggedClass<Self>(...)`" : Class<Self, Struct<{ [K in string | number | symbol]: {
readonly _tag: tag<Tag>;
} & S["fields"][K] }>, Brand>;
}

Example Defining a tagged class

import { Schema } from "effect"
class Circle extends Schema.TaggedClass<Circle>()("Circle", {
radius: Schema.Number
}) {}
const c = new Circle({ radius: 5 })
c._tag // => "Circle"
c.radius // => 5

Defines a schema-backed yieldable error class with an automatically populated _tag field.

When to use

Use to define typed errors that are schema validated, yielded in Effect.gen, and matched as tagged union members.

Signature

declare const TaggedError: <Self = never, Brand = {}>(identifier?: string) => {
<Tag extends string, Fields extends Fields>(tag: Tag, fields: Fields, annotations?: Declaration<Self, readonly [TaggedStruct<Tag, Fields>]>): [Self] extends [never] ? "Missing `Self` generic - use `class Self extends Schema.TaggedError<Self>(...)`" : Class<Self, TaggedStruct<Tag, Fields>, YieldableError & Brand>;
<Tag extends string, S extends Struct<Fields>>(tag: Tag, schema: S, annotations?: Declaration<Self, readonly [Struct<{ [K in string | number | symbol]: {
readonly _tag: tag<...>;
} & S["fields"][K] }>]>): [Self] extends [never] ? "Missing `Self` generic - use `class Self extends Schema.TaggedError<Self>(...)`" : Class<Self, Struct<{ [K in string | number | symbol]: {
readonly _tag: tag<Tag>;
} & S["fields"][K] }>, YieldableError & Brand>;
}

Example Defining a tagged error class

import { Effect, Schema } from "effect"
class NotFound extends Schema.TaggedError<NotFound>()("NotFound", {
id: Schema.Number
}) {}
const program = Effect.gen(function*() {
yield* new NotFound({ id: 42 })
})
const error = await Effect.runPromise(Effect.flip(program))
error._tag // => "NotFound"
error.id // => 42

Creates a struct schema with an automatically populated _tag field.

When to use

Use to define a tagged union case from a literal tag and a set of fields.

Details

When using the make method, the _tag field is optional and will be added automatically. However, when decoding or encoding, the _tag field must be present in the input.

Signature

declare function TaggedStruct<Tag extends LiteralValue, Fields extends Fields>(value: Tag, fields: Fields): TaggedStruct<Tag, Fields>

Example Defining a tagged struct shorthand

import { Schema } from "effect"
// Defines a struct with a fixed `_tag` field
const tagged = Schema.TaggedStruct("A", {
a: Schema.String
})
// This is the same as writing:
const equivalent = Schema.Struct({
_tag: Schema.tag("A"),
a: Schema.String
})
void tagged
void equivalent

Example Accessing the literal value of the tag

import { Schema } from "effect"
const tagged = Schema.TaggedStruct("A", {
a: Schema.String
})
tagged.fields._tag.schema.literal // => "A"

Builds a discriminated union from a record of field sets, one per variant. Each key becomes the _tag literal and the value is passed to TaggedStruct. The result includes tag, cases, guards, isAnyOf, match, and matchOrElse utilities.

See

Signature

declare function TaggedUnion<CasesByTag extends Record<string, Fields>>(casesByTag: CasesByTag): TaggedUnion<{ [K in string]: TaggedStruct<K, CasesByTag[K]> }>

Example Pattern matching a discriminated union

import { Schema } from "effect"
const Shape = Schema.TaggedUnion({
Circle: { radius: Schema.Number },
Rectangle: { width: Schema.Number, height: Schema.Number }
})
// Pattern-match on a decoded value
const area = Shape.match({ _tag: "Circle", radius: 5 }, {
Circle: (c) => Math.PI * c.radius ** 2,
Rectangle: (r) => r.width * r.height
})
Math.round(area * 100) / 100 // => 78.54

Creates a schema that validates strings by matching ordered template literal parts.

When to use

Use when the decoded value should remain the matched string and you do not need the individual template parts parsed into a tuple.

Details

Each part can be a literal string, number, or bigint, or a schema whose encoded type is string, number, or bigint. Checks on string, number, and bigint schema parts are applied while matching each segment.

Gotchas

Parts must not contain encodings, including inside unions or nested templates. Construction throws for transformed parts even when their decoded and encoded types are the same. Use TemplateLiteralParser to decode transformed parts. Brands and supported checks without encodings remain valid.

See

Signature

declare function TemplateLiteral<Parts extends Parts>(parts: Parts): TemplateLiteral<Parts>

Example Defining a URL path pattern

import { Schema } from "effect"
const schema = Schema.TemplateLiteral(["/user/", Schema.Number])
Schema.is(schema)("/user/123") // => true

Schema for parsing matched template literal strings into typed tuple parts.

When to use

Use to validate a template literal string and decode the matched parts into typed values.

Details

Unlike TemplateLiteral, this schema decodes the matched string into a readonly tuple with one element per schema part. Checks on string, number, and bigint schema parts are applied while matching each segment. The source template uses the encoded sides of the parts; the tuple retains their transformations, checks, and decoding and encoding service requirements.

Gotchas

Ambiguous templates use greedy segmentation with backtracking. Encoding a tuple and decoding the resulting string can therefore produce a different tuple when a segment contains a separator used by the template.

See

  • TemplateLiteral for a validation-only version that keeps the string encoded.

Signature

declare function TemplateLiteralParser<Parts extends Parts>(parts: Parts): TemplateLiteralParser<Parts>

Example Parsing path parameters

import { Schema } from "effect"
const schema = Schema.TemplateLiteralParser(["/user/", Schema.NumberFromString])
Schema.decodeSync(schema)("/user/42") // => ["/user/", 42]

Returns an identity Iso over the schema's focus (Iso) side.

Signature

declare function toIsoFocus<S extends Constraint>(schema: S): Iso<S["Iso"], S["Iso"]>

Returns an identity Iso over the schema's source (Type) side.

Signature

declare function toIsoSource<S extends Constraint>(schema: S): Iso<S["Type"], S["Type"]>
Since v3.10.0

Defines a fixed-length tuple schema from an array of element schemas.

Signature

declare function Tuple<Elements extends readonly Array<Constraint>>(elements: Elements): Tuple<Elements>

Example Defining a pair of string and number

import { Schema } from "effect"
const schema = Schema.Tuple([Schema.String, Schema.Number])
Schema.decodeUnknownSync(schema)(["hello", 42]) // => ["hello", 42]

Extends a fixed-length tuple schema with a variadic rest segment.

Details

The resulting tuple starts with the fixed elements from schema. The first schema in rest is the repeatable element schema, and any additional schemas in rest are required trailing tuple elements after the variadic segment. For example, [Schema.Boolean, Schema.String] represents zero or more booleans followed by a final string.

Signature

declare function TupleWithRest<S extends Tuple<Elements>, Rest extends readonly [Constraint, Constraint]>(schema: S, rest: Rest): TupleWithRest<S, Rest>

Example Defining tuples with rest elements

import { Schema } from "effect"
// [string, number, ...boolean[]]
const schema = Schema.TupleWithRest(
Schema.Tuple([Schema.String, Schema.Number]),
[Schema.Boolean]
)
Schema.decodeUnknownSync(schema)(["hello", 1, true, false]) // => ["hello", 1, true, false]

Creates a union schema of S | undefined.

Signature

declare const UndefinedOr: UndefinedOrLambda
Since v3.10.0

Creates a union schema from an array of member schemas. Members are tested in order; the first match is returned.

Details

Optionally, specify mode:

  • "anyOf" (default) โ€” matches if any member matches.
  • "oneOf" โ€” matches if exactly one member matches.

Signature

declare function Union<Members extends readonly Array<Constraint>>(members: Members, options?: UnionOptions): Union<Members>

Example Defining a string or number union

import { Schema } from "effect"
const schema = Schema.Union([Schema.String, Schema.Number])
Schema.decodeUnknownSync(schema)("hello") // => "hello"
Schema.decodeUnknownSync(schema)(42) // => 42

Returns a new array schema that ensures all elements are unique.

Details

The equivalence used to determine uniqueness is the one provided by Schema.toEquivalence(item).

Signature

declare function UniqueArray<S extends Constraint>(item: S): UniqueArray<S>

Creates a schema for a specific symbol. Only that exact symbol satisfies the schema.

Gotchas

Only globally registered symbols have a JSON encoding. Their canonical JSON form is the exact string returned by String(symbol). A local symbol cannot be encoded as JSON.

See

  • Symbol for a schema that accepts any symbol.

Signature

declare function UniqueSymbol<sym extends symbol>(symbol: sym): UniqueSymbol<sym>

Example Defining a specific symbol

import { Schema } from "effect"
const mySymbol = Symbol.for("mySymbol")
const schema = Schema.UniqueSymbol(mySymbol)
Schema.decodeSync(schema)(mySymbol) === mySymbol // => true

Attaches a constructor default value to a schema field.

Details

Constructor defaults are applied only during make*, not during decoding or encoding. Failures are represented directly as SchemaIssue.Issue values.

Signature

declare function withConstructorDefault<S extends Constraint & WithoutConstructorDefault>(defaultValue: Effect<S["~type.make.in"], Issue>): (schema: S) => withConstructorDefault<S>

Example Defining an optional field with a static default

import { Effect, Schema } from "effect"
const MySchema = Schema.Struct({
name: Schema.String.pipe(
Schema.optionalKey,
Schema.withConstructorDefault(Effect.succeed("anonymous"))
)
})
MySchema.make({}).name // => "anonymous"
Since v3.10.0

Type-level representation returned by withConstructorDefault.

Signature

interface withConstructorDefault<S extends Constraint & WithoutConstructorDefault> extends BottomLazy<S["ast"], withConstructorDefault<S>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], "with-default", S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly schema: S;
readonly Type: S["Type"];
}

Converting

Allows array schemas to decode from either an array input or a single value input.

When to use

Use when you need to accept transport formats that may represent a single-item array as a bare value, such as query-string or form-data adapters.

Gotchas

This combinator is intentionally not part of toCodecStringTree; it adds a decoding convenience rather than a canonical StringTree representation. It does not parse comma-separated strings.

Signature

declare const toCodecArrayFromSingle: <S extends Constraint>(schema: S) => toCodecArrayFromSingle<S>
Since v4.0.0

Type-level representation returned by toCodecArrayFromSingle.

Signature

interface toCodecArrayFromSingle<S extends Constraint> extends BottomLazy<S["ast"], toCodecArrayFromSingle<S>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly Type: S["Type"];
}

Derives an isomorphism codec from a schema. The encoded form is the schema's Iso type โ€” the intermediate representation used for round-tripping.

Details

Annotation links may be asynchronous, may fail, and may use optional services; the consuming parser chooses the execution and failure handling.

Gotchas

Links cannot require services because the returned Codec does not expose service requirements.

Signature

declare const toCodecIso: <S extends Constraint>(schema: S) => Codec<S["Type"], S["Iso"]>

Derives a canonical JSON codec from a schema. The encoded form is Json, and decoding produces the schema's Type.

Details

Derivation does not run transformations. Annotation links may be asynchronous, may fail, and may use optional services; the consuming parser chooses the execution and failure handling. Because hooks do not widen the returned service types, links cannot require services not declared by the input schema.

Gotchas

Declarations without a toCodecJson or toCodec annotation use Json as their encoded schema. This keeps codec construction total, but encoding or decoding can still fail when declaration values are not JSON values. A toCodecJson callback can return undefined when the declaration is already in canonical JSON form. When derivation adds an artificial transformation, checks and annotations remain on its source node rather than being copied to the JSON target. Source checks still run after the transformation.

Signature

declare const toCodecJson: <S extends Constraint>(schema: S) => toCodecJson<S>

toCodecJson

interface
Since v4.0.0

Type-level representation returned by toCodecJson.

Signature

interface toCodecJson<S extends Constraint> extends BottomLazy<S["ast"], toCodecJson<S>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: Json;
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly schema: S;
readonly Type: S["Type"];
}

Converts a schema to the StringTree canonical codec, where every leaf value becomes a string while preserving the original structure.

Details

Derivation does not run transformations. Annotation links may be asynchronous, may fail, and may use optional services; the consuming parser chooses the execution and failure handling. Links cannot require services not declared by the input schema because hooks do not widen the returned service types.

Gotchas

Declarations must provide a structural toCodecStringTree, toCodecJson, or toCodec encoding. A callback can return undefined when the declaration is already in canonical StringTree form.

Signature

declare const toCodecStringTree: <S extends Constraint>(schema: S) => toCodecStringTree<S>
Since v4.0.0

Type-level representation returned by toCodecStringTree.

Signature

interface toCodecStringTree<S extends Constraint> extends BottomLazy<S["ast"], toCodecStringTree<S>, ReadonlyArray<Constraint>, S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: StringTree;
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly schema: S;
readonly Type: S["Type"];
}

Derives a JSON Patch differ from a codec. Serializes values to JSON (via toCodecJson), computes RFC 6902 JSON Patch operations between old and new values, and can apply patches back to the typed value.

Details

diff encodes both values before computing the patch. patch encodes the old value, applies the patch to its JSON representation, and decodes the result.

Gotchas

This API runs synchronously, so failing, asynchronous, or service-dependent transformations can throw. Schema failures use "Schema validation failed" with a SchemaIssue.Issue in cause; format it with SchemaIssue.makeFormatterDefault(). Invalid patch operations instead produce JsonPatch.apply errors.

Signature

declare function toDifferJsonPatch<T>(schema: ConstraintCodec<T, unknown>): Differ<T, JsonPatch>
Since v4.0.0

Derives an Iso optic from a schema that isomorphically converts between the schema's Type and its Iso (intermediate / serialized form).

Details

Reading through the Iso encodes the schema value, while replacing through it decodes the new focus.

Gotchas

This API runs synchronously, so failing, asynchronous, or service-dependent transformations can throw. Schema failures use "Schema validation failed" with a SchemaIssue.Issue in cause; format it with SchemaIssue.makeFormatterDefault(). Consume toCodecIso with an effectful parser for asynchronous execution or explicit failure handling.

Signature

declare function toIso<S extends Constraint>(schema: S): Iso<S["Type"], S["Iso"]>

Returns a JSON Schema document using draft 2020-12.

When to use

Use when you need a draft-2020-12 description of the canonical JSON form of a runtime schema.

Details

The document describes the encoded side of Schema.toCodecJson(schema). Use that codec to decode JSON inputs. For example, it decodes JSON null to JavaScript undefined for a field defined with Schema.optional(Schema.String). Decoding the same input with the original schema rejects null.

The options parameter controls reference extraction and generation details such as excess properties and synthesized check descriptions; it does not change the draft target. The reference policy receives canonical JSON encoded ASTs. By default, anonymous non-recursive candidates remain inline, while candidates with resolved identifiers become definitions. Declarations are lowered through their toCodecJson or toCodec annotation when available before the representation document is compiled.

The generated document is intended for preliminary validation. JSON Schema and Effect checks do not always have identical semantics, so the Effect decoder remains the final authority. Passing JSON Schema validation does not guarantee that Effect decoding will succeed.

Gotchas

JSON Schema generation is best-effort. String length uses Unicode code points in JSON Schema and UTF-16 code units in Effect. A generated pattern cannot retain JavaScript RegExp flags. Object property checks apply to the original input in JSON Schema but to the decoded object in Effect. When a oneOf branch contains a known approximation, the compiler emits anyOf so that the approximation cannot create a false rejection. Unions with only exact branches retain oneOf. Custom toJsonSchema callbacks return [schema, true] for safe, looser approximations and are responsible for the semantics they declare. When canonical JSON derivation adds an artificial transformation, checks and annotations on its source node are not copied to the JSON target, so they do not appear in the emitted document. Opaque declarations without a structural codec are represented by an unconstrained JSON Schema. The default onExcessProperty: "ignore" matches the decoder default and leaves index-signature keys without exact selectors open. In "error" mode, the compiler constrains those keys with propertyNames and applies a permissive choice of candidate index value schemas. The Effect decoder enforces the exact key-value association.

See

Signature

declare function toJsonSchemaDocument(schema: Constraint, options?: ToJsonSchemaOptions): Document<"draft-2020-12">

Example Decoding JSON with the matching codec

import { Schema } from "effect"
const schema = Schema.Struct({
name: Schema.optional(Schema.String)
})
const document = Schema.toJsonSchemaDocument(schema)
const jsonCodec = Schema.toCodecJson(schema)
Schema.decodeUnknownResult(schema)({ name: null })._tag // => "Failure"
Schema.decodeUnknownSync(jsonCodec)({ name: null }) // => { name: undefined }
Schema.decodeUnknownSync(jsonCodec)({}) // => {}
Schema.encodeSync(jsonCodec)({ name: undefined }) // => { name: null }

Derives an intermediate SchemaRepresentation.Document from the encoded side of a schema.

When to use

Use when you have a Schema and need its live structural representation for inspection, persistence, or compilation.

Details

Use toType before this function to represent the type side instead. The optional reference policy controls which candidates are extracted into the document's reference table. By default, only candidates with a resolved identifier become references; recursive candidates always require one. TypeScript-only distinctions such as those added by brand are not part of the schema AST and are therefore omitted.

See

Signature

declare function toRepresentation(schema: Constraint, options?: ToRepresentationOptions): Document

Converts a schema to an experimental Standard JSON Schema V1 representation.

Signature

declare function toStandardJSONSchemaV1<S extends Constraint>(self: S): StandardJSONSchemaV1<S["Encoded"], S["Type"]> & S

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

Details

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.

Signature

declare function toStandardSchemaV1<S extends ConstraintDecoder<unknown, never>>(self: S, options?: {
readonly checkHook?: CheckHook;
readonly leafHook?: LeafHook;
readonly parseOptions?: ParseOptions;
}): StandardSchemaV1<S["Encoded"], S["Type"]> & S

Example Creating a standard schema from a regular schema

import { Schema } from "effect"
// Define custom hook functions for error formatting
const leafHook = (issue: any) => {
switch (issue._tag) {
case "InvalidType":
return "Expected different type"
case "InvalidValue":
return "Invalid value provided"
case "MissingKey":
return "Required property missing"
case "UnexpectedKey":
return "Unexpected property found"
case "Forbidden":
return "Operation not allowed"
case "OneOf":
return "Multiple valid options available"
default:
return "Validation error"
}
}
// Create a standard schema from a regular schema
const PersonSchema = Schema.Struct({
name: Schema.NonEmptyString,
age: Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 150 }))
})
const standardSchema = Schema.toStandardSchemaV1(PersonSchema, {
leafHook
})
// The standard schema can be used with any Standard Schema v1 compatible library
const validResult = standardSchema["~standard"].validate({
name: "Alice",
age: 30
})
const invalidResult = standardSchema["~standard"].validate({
name: "",
age: 200
})
if (validResult instanceof Promise || invalidResult instanceof Promise) {
throw new Error("Expected synchronous validation")
}
if ("value" in validResult) {
validResult.value // => { name: "Alice", age: 30 }
}
invalidResult.issues?.map((issue) => issue.path) // => [["name"], ["age"]]

Decoding

Decodes a typed input (the schema's Encoded type) against a schema, returning an Effect that succeeds with the decoded value or fails with a SchemaError.

When to use

Use when you need to decode input already typed as the schema's Encoded type in an Effect whose failure channel is SchemaError.

Details

For unknown input use decodeUnknownEffect. Options may be provided either when creating the decoder or when applying it; application options override creation options.

See

Signature

declare const decodeEffect: <S extends Constraint>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Effect.Effect<S["Type"], SchemaError, S["DecodingServices"]>

Decodes a typed input (the schema's Encoded type) against a schema synchronously, returning an Exit that is either a Success with the decoded value or a Failure.

When to use

Use when you need to decode already typed Encoded input into an Exit and capture schema mismatches as SchemaError.

Details

Only usable with schemas that have no DecodingServices requirement. For unknown input use decodeUnknownExit. Options may be provided either when creating the decoder or when applying it; application options override creation options. Schema mismatches are represented by a Failure cause containing SchemaError.

Gotchas

Schema issue fail reasons are wrapped as SchemaError. Defects, interruptions, and other non-schema reasons remain in the returned Cause, including when they are mixed with schema issues.

See

Signature

declare const decodeExit: <S extends ConstraintDecoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Exit_.Exit<S["Type"], SchemaError>

Decodes a typed input (the schema's Encoded type) against a schema, returning an Option that is Some with the decoded value on success or None for schema mismatches.

When to use

Use when you already have input typed as the schema's Encoded type and only need to know whether decoding succeeded.

Details

For unknown input use decodeUnknownOption. Options may be provided either when creating the decoder or when applying it; application options override creation options.

Gotchas

Only causes made entirely of schema issues are converted to None. Causes that contain defects, interruptions, or other non-schema reasons throw instead.

Signature

declare const decodeOption: <S extends ConstraintDecoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Option_.Option<S["Type"]>

Decodes a typed input (the schema's Encoded type) against a schema, returning a Promise that resolves with the decoded value or rejects with a SchemaError for schema mismatches.

When to use

Use when you already have input typed as the schema's Encoded type and need decoding to return a JavaScript Promise that rejects with SchemaError for schema mismatches.

Details

For unknown input use decodeUnknownPromise. Options may be provided either when creating the decoder or when applying it; application options override creation options.

Gotchas

Non-schema failures may reject with a runtime failure instead of SchemaError.

See

Signature

declare const decodePromise: <S extends ConstraintDecoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Promise<S["Type"]>

Decodes a typed input (the schema's Encoded type) against a schema, returning a Result that succeeds with the decoded value or fails with a SchemaError for schema mismatches.

When to use

Use when you already have input typed as the schema's Encoded type and want schema mismatches returned as Result.fail with SchemaError.

Details

For unknown input use decodeUnknownResult. Options may be provided either when creating the decoder or when applying it; application options override creation options. Schema mismatches are returned as Result.fail with SchemaError.

Gotchas

Only causes made entirely of schema issues are returned as Result.fail. Causes that contain defects, interruptions, or other non-schema reasons throw instead.

See

Signature

declare const decodeResult: <S extends ConstraintDecoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Result_.Result<S["Type"], SchemaError>

Decodes a typed input (the schema's Encoded type) against a schema synchronously, returning the decoded value or throwing a SchemaError for schema mismatches.

When to use

Use when you already have input typed as the schema's Encoded type and want schema mismatches to throw SchemaError synchronously.

Details

For unknown input use decodeUnknownSync. Only service-free schemas can be decoded synchronously. Options may be provided either when creating the decoder or when applying it; application options override creation options.

Gotchas

Non-schema failures may throw a runtime failure instead of SchemaError.

See

Signature

declare const decodeSync: <S extends ConstraintDecoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => S["Type"]

Decodes an unknown input against a schema, returning an Effect that succeeds with the decoded value or fails with a SchemaError.

When to use

Use when you need to decode unknown input in an Effect whose failure channel is SchemaError.

Details

Prefer decodeEffect when the input is already typed as the schema's Encoded type. Options may be provided either when creating the decoder or when applying it; application options override creation options.

See

Signature

declare function decodeUnknownEffect<S extends Constraint>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => Effect<S["Type"], SchemaError, S["DecodingServices"]>

Decodes an unknown input against a schema synchronously, returning an Exit that is either a Success with the decoded value or a Failure.

When to use

Use when you need to decode unknown input into an Exit and capture schema mismatches as SchemaError.

Details

Only usable with schemas that have no DecodingServices requirement. Prefer decodeExit when the input is already typed as the schema's Encoded type. Options may be provided either when creating the decoder or when applying it; application options override creation options. Schema mismatches are represented by a Failure cause containing SchemaError.

Gotchas

Schema issue fail reasons are wrapped as SchemaError. Defects, interruptions, and other non-schema reasons remain in the returned Cause, including when they are mixed with schema issues.

See

Signature

declare function decodeUnknownExit<S extends ConstraintDecoder<unknown, never>>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => Exit<S["Type"], SchemaError>

Decodes an unknown input against a schema, returning an Option that is Some with the decoded value on success or None for schema mismatches.

When to use

Use when you do not know the input type statically and only need to know whether decoding succeeded.

Details

Prefer this over decodeUnknownExit or decodeUnknownEffect when you don't need error details. For input already typed as the schema's Encoded type use decodeOption. Options may be provided either when creating the decoder or when applying it; application options override creation options.

Gotchas

Only causes made entirely of schema issues are converted to None. Causes that contain defects, interruptions, or other non-schema reasons throw instead.

Signature

declare const decodeUnknownOption: <S extends ConstraintDecoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: unknown, options?: SchemaAST.ParseOptions) => Option_.Option<S["Type"]>

Decodes an unknown input against a schema, returning a Promise that resolves with the decoded value or rejects with a SchemaError for schema mismatches.

When to use

Use when you need decoding of unknown input to return a JavaScript Promise that rejects with SchemaError for schema mismatches.

Details

For input already typed as the schema's Encoded type use decodePromise. Options may be provided either when creating the decoder or when applying it; application options override creation options.

Gotchas

Non-schema failures may reject with a runtime failure instead of SchemaError.

See

Signature

declare function decodeUnknownPromise<S extends ConstraintDecoder<unknown, never>>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => Promise<S["Type"]>

Decodes an unknown input against a schema, returning a Result that succeeds with the decoded value or fails with a SchemaError for schema mismatches.

When to use

Use when you do not know the input type statically and want schema mismatches returned as Result.fail with SchemaError.

Details

For input already typed as the schema's Encoded type use decodeResult. Options may be provided either when creating the decoder or when applying it; application options override creation options. Schema mismatches are returned as Result.fail with SchemaError.

Gotchas

Only causes made entirely of schema issues are returned as Result.fail. Causes that contain defects, interruptions, or other non-schema reasons throw instead.

See

Signature

declare function decodeUnknownResult<S extends ConstraintDecoder<unknown, never>>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => Result<S["Type"], SchemaError>

Decodes an unknown input against a schema synchronously, returning the decoded value or throwing a SchemaError for schema mismatches.

When to use

Use when you need to validate unknown data at a synchronous boundary and want schema mismatches to throw SchemaError.

Details

For input already typed as the schema's Encoded type use decodeSync. Only service-free schemas can be decoded synchronously. For alternatives that do not throw on schema mismatches, see decodeUnknownOption, decodeUnknownExit, or decodeUnknownEffect. Options may be provided either when creating the decoder or when applying it; application options override creation options.

Gotchas

Non-schema failures may throw a runtime failure instead of SchemaError.

See

Signature

declare function decodeUnknownSync<S extends ConstraintDecoder<unknown, never>>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => S["Type"]

Example Decoding with a transformation schema

import { Schema } from "effect"
const NumberFromString = Schema.NumberFromString
Schema.decodeUnknownSync(NumberFromString)("42") // => 42

Schema for decoding FormData through a bracket-notation tree.

When to use

Use to decode browser or multipart form data into a structured schema value.

Details

The decoding process has two steps:

  1. Parse FormData into a nested tree record.
  2. Decode the parsed value with the given schema.

You can express nested values using bracket notation.

If you want to decode string fields into non-string primitive values, use Schema.toCodecStringTree.

Signature

declare function fromFormData<S extends Constraint>(schema: S): fromFormData<S>

Example Decoding a flat structure

import { Schema } from "effect"
const schema = Schema.fromFormData(
Schema.Struct({
a: Schema.String
})
)
const formData = new FormData()
formData.append("a", "1")
formData.append("b", "2")
Schema.decodeUnknownSync(schema)(formData) // => { a: "1" }

Example Decoding nested fields

import { Schema } from "effect"
const schema = Schema.fromFormData(
Schema.Struct({
a: Schema.String,
b: Schema.Struct({
c: Schema.String,
d: Schema.String
})
})
)
const formData = new FormData()
formData.append("a", "1")
formData.append("b[c]", "2")
formData.append("b[d]", "3")
Schema.decodeUnknownSync(schema)(formData) // => { a: "1", b: { c: "2", d: "3" } }

Example Parsing non-string values

import { Schema } from "effect"
const schema = Schema.fromFormData(
Schema.toCodecStringTree(
Schema.Struct({
a: Schema.Int
})
)
)
const formData = new FormData()
formData.append("a", "1")
Schema.decodeUnknownSync(schema)(formData) // => { a: 1 }

Schema for decoding URLSearchParams through a bracket-notation tree.

When to use

Use to decode query parameters into a structured schema value.

Details

The decoding process has two steps:

  1. Parse URLSearchParams into a nested tree record.
  2. Decode the parsed value with the given schema.

You can express nested values using bracket notation.

If you want to decode values that are not strings, use Schema.toCodecStringTree. This serializer preserves values such as numbers when compatible with the schema.

Signature

declare function fromURLSearchParams<S extends Constraint>(schema: S): fromURLSearchParams<S>

Example Decoding a flat structure

import { Schema } from "effect"
const schema = Schema.fromURLSearchParams(
Schema.Struct({
a: Schema.String
})
)
const urlSearchParams = new URLSearchParams("a=1&b=2")
Schema.decodeUnknownSync(schema)(urlSearchParams) // => { a: "1" }

Example Decoding nested fields

import { Schema } from "effect"
const schema = Schema.fromURLSearchParams(
Schema.Struct({
a: Schema.String,
b: Schema.Struct({
c: Schema.String,
d: Schema.String
})
})
)
const urlSearchParams = new URLSearchParams("a=1&b[c]=2&b[d]=3")
Schema.decodeUnknownSync(schema)(urlSearchParams) // => { a: "1", b: { c: "2", d: "3" } }

Example Parsing non-string values

import { Schema } from "effect"
const schema = Schema.fromURLSearchParams(
Schema.toCodecStringTree(
Schema.Struct({
a: Schema.Int
})
)
)
const urlSearchParams = new URLSearchParams("a=1&b=2")
Schema.decodeUnknownSync(schema)(urlSearchParams) // => { a: 1 }

Intercepts the decoding pipeline of a schema.

Details

The provided function receives the current decoding Effect and ParseOptions, and returns a new Effect โ€” potentially adding service requirements (RD), recovering from errors, or augmenting the result.

See

Signature

declare function middlewareDecoding<S extends Constraint, RD>(decode: (effect: Effect<Option<S["Type"]>, Issue, S["DecodingServices"]>, options: ParseOptions) => Effect<Option<S["Type"]>, Issue, RD>): (schema: S) => middlewareDecoding<S, RD>

Example Logging decode failures

import { Effect, Schema } from "effect"
const events: Array<string> = []
const Logged = Schema.String.pipe(
Schema.middlewareDecoding((effect) =>
Effect.tapError(effect, () => Effect.sync(() => events.push("decode failed")))
)
)
Effect.runSync(Effect.result(Schema.decodeUnknownEffect(Logged)(42)))
events // => ["decode failed"]
Since v4.0.0

Type-level representation returned by middlewareDecoding.

Signature

interface middlewareDecoding<S extends Constraint, RD> extends BottomLazy<S["ast"], middlewareDecoding<S, RD>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: RD;
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly schema: S;
readonly Type: S["Type"];
}

Wraps the Encoded side with optional (key absent or undefined) and provides a default Encoded value when the field is missing or undefined during decoding.

When to use

Use when the default is expressed in the encoded representation, before the field's decoding transformation runs.

Details

The default value is specified in terms of the Encoded type (before any decoding transformations).

Options:

  • encodingStrategy:
    • "passthrough" (default): include the value in the encoded output.
    • "omit": omit the key from the encoded output.

See

Signature

declare function withDecodingDefault<S extends Constraint, R = never>(defaultValue: Effect<S["Encoded"], SchemaError, R>, options?: DecodingDefaultOptions): (self: S) => withDecodingDefault<S, R>

Example Providing a default for an optional field value

import { Effect, Schema } from "effect"
const MySchema = Schema.Struct({
name: Schema.String.pipe(Schema.optional, Schema.withDecodingDefault(Effect.succeed("anonymous")))
})
Schema.decodeUnknownSync(MySchema)({ name: undefined }).name // => "anonymous"
Since v3.10.0

Type-level representation returned by withDecodingDefault.

Signature

interface withDecodingDefault<S extends Constraint, R = never> extends decodeTo<S, optional<toEncoded<S>>, R> {
constructor(_: never);
readonly Rebuild: withDecodingDefault<S, R>;
}

Makes a struct key optional on the Encoded side and provides a default Encoded value when the key is missing during decoding.

Details

The key uses optionalKey on the encoded side, so it may be absent from the input object but not undefined. The default value is specified in terms of the Encoded type (before any decoding transformations).

Options:

  • encodingStrategy:
    • "passthrough" (default): include the value in the encoded output.
    • "omit": omit the key from the encoded output.

See

Signature

declare function withDecodingDefaultKey<S extends Constraint, R = never>(defaultValue: Effect<S["Encoded"], SchemaError, R>, options?: DecodingDefaultOptions): (self: S) => withDecodingDefaultKey<S, R>

Example Providing a default for a missing struct key

import { Effect, Schema } from "effect"
const MySchema = Schema.Struct({
name: Schema.String.pipe(Schema.withDecodingDefaultKey(Effect.succeed("anonymous")))
})
Schema.decodeUnknownSync(MySchema)({}).name // => "anonymous"
Since v4.0.0

Type-level representation returned by withDecodingDefaultKey.

Signature

interface withDecodingDefaultKey<S extends Constraint, R = never> extends decodeTo<S, optionalKey<toEncoded<S>>, R> {
constructor(_: never);
readonly Rebuild: withDecodingDefaultKey<S, R>;
}

Wraps the Encoded side with optional (key absent or undefined) and provides a default Type value when the field is missing or undefined during decoding.

When to use

Use when the default is already in the decoded representation and should not pass through the field's decoding transformation.

Details

Unlike withDecodingDefault, the default value is specified in terms of the Type (decoded) representation, so it does not need to go through the decoding transformation.

Options:

  • encodingStrategy:
    • "passthrough" (default): include the value in the encoded output.
    • "omit": omit the key from the encoded output.

See

Signature

declare function withDecodingDefaultType<S extends Constraint, R = never>(defaultValue: Effect<S["Type"], SchemaError, R>, options?: DecodingDefaultOptions): (self: S) => withDecodingDefaultType<S, R>
Since v4.0.0

Type-level representation returned by withDecodingDefaultType.

Signature

interface withDecodingDefaultType<S extends Constraint, R = never> extends decodeTo<withDecodingDefault<toType<S>, R>, optional<S>> {
constructor(_: never);
readonly Rebuild: withDecodingDefaultType<S, R>;
}

Makes a struct key optional on the Encoded side (optionalKey, so the key may be absent but not undefined) and provides a default Type value when the key is missing during decoding.

Details

Unlike withDecodingDefaultKey, the default value is specified in terms of the Type (decoded) representation, so it does not need to go through the decoding transformation.

Options:

  • encodingStrategy:
    • "passthrough" (default): include the value in the encoded output.
    • "omit": omit the key from the encoded output.

See

Signature

declare function withDecodingDefaultTypeKey<S extends Constraint, R = never>(defaultValue: Effect<S["Type"], SchemaError, R>, options?: DecodingDefaultOptions): (self: S) => withDecodingDefaultTypeKey<S, R>

Type-level representation returned by withDecodingDefaultTypeKey.

Signature

interface withDecodingDefaultTypeKey<S extends Constraint, R = never> extends decodeTo<withDecodingDefaultKey<toType<S>, R>, optionalKey<S>> {
constructor(_: never);
readonly Rebuild: withDecodingDefaultTypeKey<S, R>;
}

Encoding

Encodes a typed input (the schema's Type) against a schema, returning an Effect that succeeds with the encoded value or fails with a SchemaError.

When to use

Use when you need to encode input already typed as the schema's Type in an Effect whose failure channel is SchemaError.

Details

For unknown input use encodeUnknownEffect. Options may be provided either when creating the encoder or when applying it; application options override creation options.

See

Signature

declare const encodeEffect: <S extends Constraint>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Effect.Effect<S["Encoded"], SchemaError, S["EncodingServices"]>

Encodes a typed input (the schema's Type) against a schema synchronously, returning an Exit that is either a Success with the encoded value or a Failure.

When to use

Use when you need to encode already typed schema values into an Exit and capture schema mismatches as SchemaError.

Details

Only usable with schemas that have no EncodingServices requirement. For unknown input use encodeUnknownExit. Options may be provided either when creating the encoder or when applying it; application options override creation options. Schema mismatches are represented by a Failure cause containing SchemaError.

Gotchas

Schema issue fail reasons are wrapped as SchemaError. Defects, interruptions, and other non-schema reasons remain in the returned Cause, including when they are mixed with schema issues.

See

Signature

declare const encodeExit: <S extends ConstraintEncoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Exit_.Exit<S["Encoded"], SchemaError>

Encodes a typed input (the schema's Type) against a schema, returning an Option that is Some with the encoded value on success or None for schema mismatches.

When to use

Use when you already have a value typed as the schema's Type and only need to know whether encoding succeeded.

Details

For unknown input use encodeUnknownOption. Options may be provided either when creating the encoder or when applying it; application options override creation options.

Gotchas

Only causes made entirely of schema issues are converted to None. Causes that contain defects, interruptions, or other non-schema reasons throw instead.

Signature

declare const encodeOption: <S extends ConstraintEncoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Option_.Option<S["Encoded"]>

Encodes a typed input (the schema's Type) against a schema, returning a Promise that resolves with the encoded value or rejects with a SchemaError for schema mismatches.

When to use

Use when you already have a value typed as the schema's Type and need encoding to return a JavaScript Promise that rejects with SchemaError for schema mismatches.

Details

For unknown input use encodeUnknownPromise. Options may be provided either when creating the encoder or when applying it; application options override creation options.

Gotchas

Non-schema failures may reject with a runtime failure instead of SchemaError.

See

Signature

declare const encodePromise: <S extends ConstraintEncoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Promise<S["Encoded"]>

Encodes a typed input (the schema's Type) against a schema, returning a Result that succeeds with the encoded value or fails with a SchemaError for schema mismatches.

When to use

Use when you already have a value typed as the schema's Type and want schema mismatches returned as Result.fail with SchemaError.

Details

For unknown input use encodeUnknownResult. Options may be provided either when creating the encoder or when applying it; application options override creation options. Schema mismatches are returned as Result.fail with SchemaError.

Gotchas

Only causes made entirely of schema issues are returned as Result.fail. Causes that contain defects, interruptions, or other non-schema reasons throw instead.

See

Signature

declare const encodeResult: <S extends ConstraintEncoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Result_.Result<S["Encoded"], SchemaError>

Encodes a typed input (the schema's Type) against a schema synchronously, throwing a SchemaError for schema mismatches.

When to use

Use when you already have a value typed as the schema's Type and want schema mismatches to throw SchemaError synchronously.

Details

For unknown input use encodeUnknownSync. Options may be provided either when creating the encoder or when applying it; application options override creation options.

Gotchas

Non-schema failures may throw a runtime failure instead of SchemaError.

See

Signature

declare const encodeSync: <S extends ConstraintEncoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: S["Type"], options?: SchemaAST.ParseOptions) => S["Encoded"]

Encodes an unknown input against a schema, returning an Effect that succeeds with the encoded value or fails with a SchemaError.

When to use

Use when you need to encode unknown input in an Effect whose failure channel is SchemaError.

Details

Prefer encodeEffect when the value is already typed as the schema's Type. Options may be provided either when creating the encoder or when applying it; application options override creation options.

See

Signature

declare function encodeUnknownEffect<S extends Constraint>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => Effect<S["Encoded"], SchemaError, S["EncodingServices"]>

Example Encoding a value to a string

import { Effect, Schema } from "effect"
const NumberFromString = Schema.NumberFromString
await Effect.runPromise(Schema.encodeUnknownEffect(NumberFromString)(42)) // => "42"

Encodes an unknown input against a schema synchronously, returning an Exit that is either a Success with the encoded value or a Failure.

When to use

Use when you need to encode unknown input into an Exit and capture schema mismatches as SchemaError.

Details

Only usable with schemas that have no EncodingServices requirement. Prefer encodeExit when the value is already typed as the schema's Type. Options may be provided either when creating the encoder or when applying it; application options override creation options. Schema mismatches are represented by a Failure cause containing SchemaError.

Gotchas

Schema issue fail reasons are wrapped as SchemaError. Defects, interruptions, and other non-schema reasons remain in the returned Cause, including when they are mixed with schema issues.

See

Signature

declare function encodeUnknownExit<S extends ConstraintEncoder<unknown, never>>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => Exit<S["Encoded"], SchemaError>

Encodes an unknown input against a schema, returning an Option that is Some with the encoded value on success or None for schema mismatches.

When to use

Use when you do not know the input type statically and only need to know whether encoding succeeded.

Details

Prefer this over encodeUnknownExit or encodeUnknownEffect when you don't need error details. For values already typed as the schema's Type use encodeOption. Options may be provided either when creating the encoder or when applying it; application options override creation options.

Gotchas

Only causes made entirely of schema issues are converted to None. Causes that contain defects, interruptions, or other non-schema reasons throw instead.

Signature

declare const encodeUnknownOption: <S extends ConstraintEncoder<unknown>>(schema: S, options?: SchemaAST.ParseOptions) => (input: unknown, options?: SchemaAST.ParseOptions) => Option_.Option<S["Encoded"]>

Encodes an unknown input against a schema, returning a Promise that resolves with the encoded value or rejects with a SchemaError for schema mismatches.

When to use

Use when you need encoding of unknown input to return a JavaScript Promise that rejects with SchemaError for schema mismatches.

Details

For values already typed as the schema's Type use encodePromise. Options may be provided either when creating the encoder or when applying it; application options override creation options.

Gotchas

Non-schema failures may reject with a runtime failure instead of SchemaError.

See

Signature

declare function encodeUnknownPromise<S extends ConstraintEncoder<unknown, never>>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => Promise<S["Encoded"]>

Encodes an unknown input against a schema, returning a Result that succeeds with the encoded value or fails with a SchemaError for schema mismatches.

When to use

Use when you do not know the input type statically and want schema mismatches returned as Result.fail with SchemaError.

Details

For values already typed as the schema's Type use encodeResult. Options may be provided either when creating the encoder or when applying it; application options override creation options. Schema mismatches are returned as Result.fail with SchemaError.

Gotchas

Only causes made entirely of schema issues are returned as Result.fail. Causes that contain defects, interruptions, or other non-schema reasons throw instead.

See

Signature

declare function encodeUnknownResult<S extends ConstraintEncoder<unknown, never>>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => Result<S["Encoded"], SchemaError>

Encodes an unknown input against a schema synchronously, throwing a SchemaError for schema mismatches.

When to use

Use when you need to serialize unknown data at a synchronous boundary and want schema mismatches to throw SchemaError.

Details

For alternatives that do not throw on schema mismatches, see encodeUnknownOption, encodeUnknownExit, or encodeUnknownEffect. For values already typed as the schema's Type use encodeSync. Options may be provided either when creating the encoder or when applying it; application options override creation options.

Gotchas

Non-schema failures may throw a runtime failure instead of SchemaError.

See

Signature

declare function encodeUnknownSync<S extends ConstraintEncoder<unknown, never>>(schema: S, options?: ParseOptions): (input: unknown, options?: ParseOptions) => S["Encoded"]

Intercepts the encoding pipeline of a schema.

Details

The provided function receives the current encoding Effect and ParseOptions, and returns a new Effect โ€” potentially adding service requirements (RE), recovering from errors, or augmenting the result.

See

Signature

declare function middlewareEncoding<S extends Constraint, RE>(encode: (effect: Effect<Option<S["Encoded"]>, Issue, S["EncodingServices"]>, options: ParseOptions) => Effect<Option<S["Encoded"]>, Issue, RE>): (schema: S) => middlewareEncoding<S, RE>

Example Logging encode failures

import { Effect, Schema } from "effect"
const events: Array<string> = []
const Logged = Schema.String.pipe(
Schema.middlewareEncoding((effect) =>
Effect.tapError(effect, () => Effect.sync(() => events.push("encode failed")))
)
)
Effect.runSync(Effect.result(Schema.encodeUnknownEffect(Logged)(42)))
events // => ["encode failed"]
Since v4.0.0

Type-level representation returned by middlewareEncoding.

Signature

interface middlewareEncoding<S extends Constraint, RE> extends BottomLazy<S["ast"], middlewareEncoding<S, RE>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: RE;
readonly Iso: S["Iso"];
readonly schema: S;
readonly Type: S["Type"];
}

Derives an XML encoder from a codec.

Details

The returned function encodes a value through toCodecStringTree and returns an Effect that succeeds with the XML string or fails with a SchemaIssue.Issue if codec encoding fails.

Signature

declare function toEncoderXml<T, RE>(codec: ConstraintCodec<T, unknown, unknown, RE>, options?: XmlEncoderOptions): (t: T) => Effect<string, Issue, RE>

Error Handling

Recovers from a decoding error by providing a fallback value.

Details

The handler receives the Issue and returns an Effect that either succeeds with a fallback value or re-fails with a (possibly different) issue.

See

Signature

declare function catchDecoding<S extends Constraint>(f: (issue: Issue) => Effect<Option<S["Type"]>, Issue>): (self: S) => middlewareDecoding<S, S["DecodingServices"]>

Example Returning a default on decode failure

import { Effect, Option, Schema } from "effect"
const schema = Schema.Number.pipe(
Schema.catchDecoding((_issue) => Effect.succeed(Option.some(0)))
)
Effect.runSync(Schema.decodeUnknownEffect(schema)("invalid")) // => 0

Recovers from a decoding error with a handler that may require Effect services.

When to use

Use when you need decoding fallback logic to require services from the Effect context.

Details

The handler receives the Issue and returns an Effect that either succeeds with a fallback value or re-fails with a (possibly different) issue. The handler's services are added to the schema's decoding services.

See

Signature

declare function catchDecodingWithContext<S extends Constraint, R = never>(f: (issue: Issue) => Effect<Option<S["Type"]>, Issue, R>): (self: S) => middlewareDecoding<S, R | S["DecodingServices"]>

Recovers from an encoding error by providing a fallback value.

Details

The handler receives the Issue and returns an Effect that either succeeds with a fallback value or re-fails with a (possibly different) issue.

See

Signature

declare function catchEncoding<S extends Constraint>(f: (issue: Issue) => Effect<Option<S["Encoded"]>, Issue>): (self: S) => middlewareEncoding<S, S["EncodingServices"]>

Recovers from an encoding error with a handler that may require Effect services.

When to use

Use when you need encoding fallback logic to require services from the Effect context.

Details

The handler receives the Issue and returns an Effect that either succeeds with a fallback encoded value or re-fails with a (possibly different) issue. The handler's services are added to the schema's encoding services.

See

Signature

declare function catchEncodingWithContext<S extends Constraint, R = never>(f: (issue: Issue) => Effect<Option<S["Encoded"]>, Issue, R>): (self: S) => middlewareEncoding<S, R | S["EncodingServices"]>

Errors

Error thrown or returned when schema decoding or encoding fails.

Details

The issue field contains a structured SchemaIssue.Issue tree describing every validation failure, including the path to the problematic value and the expected type or constraint. The message field renders the issue tree with the default formatter.

Gotchas

Parsing with reportInput: true adds an enumerable input field to value-bearing issues. Built-in messages may include reported input, and custom annotations or messages are not sanitized.

See

Signature

declare class SchemaError extends YieldableError<this> & {
readonly _tag: "SchemaError";
} & Readonly<{
readonly issue: Issue;
}> {
constructor(issue: Issue);
readonly "~effect/Schema/SchemaError": "~effect/Schema/SchemaError";
message: string;
[NodeInspectSymbol](): {
_tag: "SchemaError";
message: string;
};
toJSON(): {
_tag: "SchemaError";
message: string;
};
toString(): string;
}

Example Inspecting a SchemaError

import { Result, Schema } from "effect"
const result = Schema.decodeUnknownResult(Schema.Number)("not a number")
const message = Result.isFailure(result) ? result.failure.message : ""
message // => "Expected number"

Filtering

Since v4.0.0

Attaches one or more filter checks to a schema without changing the TypeScript type.

Signature

declare function check<S extends Top>(...checks: readonly [Check<S["Type"]>, Check<S["Type"]>]): (self: S) => S["Rebuild"]

Example Adding checks to a schema

import { Schema } from "effect"
const AgeSchema = Schema.Finite.pipe(
Schema.check(Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(120))
)
Schema.is(AgeSchema)(42) // => true
Schema.is(AgeSchema)(121) // => false
Since v3.10.0

Narrows the TypeScript type of a schema's output via a type guard predicate, attaching the guard as a runtime filter check.

Details

The annotations parameter annotates the filter created by the refinement. With the default formatter, failed refinements use message first, expected second, and <filter> when neither is provided. identifier names type-level failures before the refinement runs; it does not name the failed refinement itself.

Signature

declare function refine<S extends Constraint, T extends unknown>(refinement: (value: S["Type"]) => value is T, annotations?: Filter): (schema: S) => refine<T, S>

refine

interface
Since v3.10.0

Type-level representation returned by refine.

Signature

interface refine<T extends S["Type"], S extends Constraint> extends BottomLazy<S["ast"], refine<T, S>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": T;
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly Iso: T;
readonly schema: S;
readonly Type: T;
}

Formatting

Attaches a custom formatter used by toFormatter.

Details

Use this when the formatter derived from the schema structure is not suitable. The annotation is applied through this helper because adding it directly to Annotations.Bottom would make schemas invariant.

Signature

declare function overrideToFormatter<S extends Top>(toFormatter: () => Formatter<S["Type"]>): (self: S) => S["Rebuild"]

Derives a string formatter function from a schema. The formatter converts a value to its human-readable string representation, recursing into structs, arrays, and unions.

Details

The optional onBefore hook lets you intercept specific AST nodes before the default formatting logic runs.

Signature

declare function toFormatter<S extends Constraint>(schema: S, options?: {
readonly onBefore?: (ast: AST, recur: (ast: AST) => Formatter<any>) => Formatter<any, string> | undefined;
}): Formatter<S["Type"]>

Getters

Resolves the typed annotations from a schema. The term "resolve" (rather than "get") reflects the lookup strategy: if the schema has checks, the annotations are taken from the last check; otherwise they are taken from the base schema instance.

Signature

declare function resolveAnnotations<S extends Constraint>(schema: S): Bottom<S["Type"], S["~type.parameters"]> | undefined

Resolves the context (key-level) annotations from a schema. Context annotations are those attached via annotateKey and live on the AST's context rather than on the schema node itself.

Signature

declare function resolveAnnotationsKey<S extends Constraint>(schema: S): Key<S["Type"]> | undefined

Guards

Since v4.0.0

Creates an assertion function that throws an error if the input does not match the schema.

When to use

Use to validate unknown input at runtime while narrowing the value with a TypeScript assertion signature.

Details

The input is narrowed if the assertion succeeds. If schema validation fails, the assertion throws an Error whose cause is SchemaIssue.Issue. Schema validation failures use the generic message "Schema validation failed". Format the cause explicitly with SchemaIssue.makeFormatterDefault() when human-readable details are needed.

Gotchas

Causes that contain defects, interruptions, or other non-schema reasons throw with the underlying Cause attached instead of being converted to schema validation errors.

Signature

declare const asserts: <S extends Constraint, I>(schema: S, input: I) => asserts input is I & S["Type"]

Example Asserting and narrowing an input

import { Schema, SchemaIssue } from "effect"
const input: unknown = "hello"
// This will pass silently (no return value) and narrow input to string
Schema.asserts(Schema.String, input)
input.toUpperCase() // => "HELLO"
// This will throw an error
try {
const invalid: unknown = 123
Schema.asserts(Schema.String, invalid)
} catch (error) {
if (error instanceof Error) {
SchemaIssue.isIssue(error.cause) // => true
}
}
Since v3.10.0

Creates a type guard function that checks if a value conforms to a given schema.

Details

This function returns a predicate that performs a type-safe check, narrowing the type of the input value if the check passes. The predicate returns false for schema mismatches.

Gotchas

Only causes made entirely of schema issues are converted to false. Causes that contain defects, interruptions, or other non-schema reasons throw instead.

Signature

declare const is: typeof SchemaParser.is

Example Defining a basic type guard

import { Schema } from "effect"
const isString = Schema.is(Schema.String)
isString("hello") // => true
isString(42) // => false
// Type narrowing in action
const value: unknown = "hello"
if (isString(value)) {
// value is now typed as string
value.toUpperCase() // => "HELLO"
}
Since v3.10.0

Checks whether a value is a Schema.

Signature

declare function isSchema(u: unknown): u is Top

Returns true if u is a SchemaError.

When to use

Use when you need to narrow an unknown value to SchemaError.

Signature

declare function isSchemaError(u: unknown): u is SchemaError

Example Narrowing Schema errors

import { Result, Schema } from "effect"
const result = Result.try(() => Schema.decodeUnknownSync(Schema.Number)("oops"))
const error: unknown = Result.isFailure(result) ? result.failure : undefined
Schema.isSchemaError(error) // => true

Instances

Overrides the equivalence derivation for a schema by supplying a custom Equivalence.

When to use

Use when you need a custom equivalence instead of the default structural equivalence derived by toEquivalence.

Signature

declare function overrideToEquivalence<S extends Top>(toEquivalence: () => Equivalence<S["Type"]>): (self: S) => S["Rebuild"]

Derives an Equivalence from a schema. Two values are considered equal when every field (and nested field) compares equal according to the schema structure.

Signature

declare function toEquivalence<T>(schema: Schema<T>): Equivalence<T>

Example Comparing structs

import { Schema } from "effect"
const eq = Schema.toEquivalence(Schema.Struct({ id: Schema.Number, name: Schema.String }))
eq({ id: 1, name: "Alice" }, { id: 1, name: "Alice" }) // => true
eq({ id: 1, name: "Alice" }, { id: 2, name: "Alice" }) // => false

Models

$Array

interface
Since v4.0.0

Type-level representation returned by Array.

Signature

interface $Array<S extends Constraint> extends BottomLazy<SchemaAST.Arrays, $Array<S>> {
constructor(_: never);
readonly "~type.make": readonly Array<S["~type.make"]>;
readonly "~type.make.in": readonly Array<S["~type.make"]>;
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: readonly Array<S["Encoded"]>;
readonly EncodingServices: S["EncodingServices"];
readonly Iso: readonly Array<S["Iso"]>;
readonly Type: readonly Array<S["Type"]>;
readonly value: S;
}

$ReadonlyMap

interface
Since v4.0.0

Type-level representation returned by ReadonlyMap.

Signature

interface $ReadonlyMap<Key extends Constraint, Value extends Constraint> extends declareConstructor<globalThis.ReadonlyMap<Key["Type"], Value["Type"]>, globalThis.ReadonlyMap<Key["Encoded"], Value["Encoded"]>, readonly [Key, Value], ReadonlyMapIso<Key, Value>> {
constructor(_: never);
readonly key: Key;
readonly Rebuild: $ReadonlyMap<Key, Value>;
readonly value: Value;
}

$ReadonlySet

interface
Since v4.0.0

Type-level representation returned by ReadonlySet.

Signature

interface $ReadonlySet<Value extends Constraint> extends declareConstructor<globalThis.ReadonlySet<Value["Type"]>, globalThis.ReadonlySet<Value["Encoded"]>, readonly [Value], ReadonlySetIso<Value>> {
constructor(_: never);
readonly Rebuild: $ReadonlySet<Value>;
readonly value: Value;
}

$Record

interface
Since v4.0.0

Type-level representation returned by Record.

Signature

interface $Record<Key extends Record.Key, Value extends Constraint> extends BottomLazy<SchemaAST.Objects, $Record<Key, Value>> {
constructor(_: never);
readonly "~type.make": { [K in string | number | symbol]: MakeIn<Key, Value>[K] };
readonly "~type.make.in": { [K in string | number | symbol]: MakeIn<Key, Value>[K] };
readonly DecodingServices: DecodingServices<Key, Value>;
readonly Encoded: Encoded<Key, Value>;
readonly EncodingServices: EncodingServices<Key, Value>;
readonly Iso: Iso<Key, Value>;
readonly key: Key;
readonly Type: Type<Key, Value>;
readonly value: Value;
}

The Annotations namespace groups all annotation interfaces used to attach metadata to schemas. Annotations control documentation, validation messages, JSON Schema generation, equivalence, arbitrary generation, and more.

Details

Use resolveAnnotations to read the annotations attached to a schema at runtime.

Any

interface
Since v3.10.0

Type-level representation of Any.

Signature

interface Any extends Bottom<any, any, never, never, SchemaAST.Any, Any> {
constructor(_: never);
}

BigDecimal

interface
Since v3.10.0

Type-level representation of BigDecimal.

Signature

interface BigDecimal extends declare<BigDecimal_.BigDecimal> {
constructor(_: never);
readonly Rebuild: BigDecimal;
}
Since v4.0.0

Type-level representation of BigDecimalFromString.

Signature

interface BigDecimalFromString extends decodeTo<BigDecimal, String> {
constructor(_: never);
readonly Rebuild: BigDecimalFromString;
}

BigInt

interface
Since v4.0.0

Type-level representation of BigInt.

Signature

interface BigInt extends Bottom<bigint, bigint, never, never, SchemaAST.BigInt, BigInt> {
constructor(_: never);
}
Since v4.0.0

Type-level representation of BigIntFromString.

Signature

interface BigIntFromString extends decodeTo<BigInt, String> {
constructor(_: never);
readonly Rebuild: BigIntFromString;
}

Boolean

interface
Since v4.0.0

Type-level representation of Boolean.

Signature

interface Boolean extends Bottom<boolean, boolean, never, never, SchemaAST.Boolean, Boolean> {
constructor(_: never);
}
Since v4.0.0

Type-level representation of BooleanFromBit.

Signature

interface BooleanFromBit extends decodeTo<Boolean, Literals<readonly [0, 1]>> {
constructor(_: never);
readonly Rebuild: BooleanFromBit;
}
Since v4.0.0

The fully-parameterized schema interface without a construct signature. Exposes all 14 type parameters controlling type inference, mutability, optionality, services, and transformation behavior.

When to use

Use as the base for schema interfaces that provide a specialized construct signature.

Signature

interface BottomWithoutNew<out T, out E, out RD, out RE, out Ast extends SchemaAST.AST, out Rebuild extends Top, out TypeMakeIn = T, out Iso = T, in out TypeParameters extends ReadonlyArray<Constraint> = readonly [], out TypeMake = TypeMakeIn, out TypeMutability extends Mutability = "readonly", out TypeOptionality extends Optionality = "required", out TypeConstructorDefault extends ConstructorDefault = "no-default", out EncodedMutability extends Mutability = "readonly", out EncodedOptionality extends Optionality = "required"> extends Pipeable {
readonly "~effect/Schema/Schema": "~effect/Schema/Schema";
readonly "~encoded.mutability": EncodedMutability;
readonly "~encoded.optionality": EncodedOptionality;
readonly "~type.constructor.default": TypeConstructorDefault;
readonly "~type.make": TypeMake;
readonly "~type.make.in": TypeMakeIn;
readonly "~type.mutability": TypeMutability;
readonly "~type.optionality": TypeOptionality;
readonly "~type.parameters": TypeParameters;
readonly ast: Ast;
readonly DecodingServices: RD;
readonly Encoded: E;
readonly EncodingServices: RE;
Iso: Iso;
Rebuild: Rebuild;
readonly Type: T;
annotate(annotations: Bottom<T, TypeParameters>): Rebuild;
annotateKey(annotations: Key<T>): Rebuild;
check(...checks: readonly [Check<T>, Check<T>]): Rebuild;
make(input: TypeMakeIn, options?: MakeOptions): T;
makeEffect(input: TypeMakeIn, options?: MakeOptions): Effect<T, Issue>;
makeOption(input: TypeMakeIn, options?: MakeOptions): Option<T>;
rebuild(ast: Ast): Rebuild;
}

ByteSize

interface unstable
Since v4.0.0

Type-level representation of ByteSize.

Signature

interface ByteSize extends declare<ByteSize_.ByteSize> {
constructor(_: never);
readonly Rebuild: ByteSize;
}

ByteSizeFromBigInt

interface unstable
Since v4.0.0

Type-level representation of ByteSizeFromBigInt.

Signature

interface ByteSizeFromBigInt extends decodeTo<ByteSize, BigInt> {
constructor(_: never);
readonly Rebuild: ByteSizeFromBigInt;
}

ByteSizeFromNumber

interface unstable
Since v4.0.0

Type-level representation of ByteSizeFromNumber.

Signature

interface ByteSizeFromNumber extends decodeTo<ByteSize, Number> {
constructor(_: never);
readonly Rebuild: ByteSizeFromNumber;
}

ByteSizeFromString

interface unstable
Since v4.0.0

Type-level representation of ByteSizeFromString.

Signature

interface ByteSizeFromString extends decodeTo<ByteSize, String> {
constructor(_: never);
readonly Rebuild: ByteSizeFromString;
}

Cause

interface
Since v3.10.0

Type-level representation returned by Cause.

Signature

interface Cause<E extends Constraint, D extends Constraint> extends declareConstructor<Cause_.Cause<E["Type"]>, Cause_.Cause<E["Encoded"]>, readonly [E, D], CauseIso<E, D>> {
constructor(_: never);
readonly defect: D;
readonly error: E;
readonly Rebuild: Cause<E, D>;
}

CauseReason

interface
Since v4.0.0

Type-level representation returned by CauseReason.

Signature

interface CauseReason<E extends Constraint, D extends Constraint> extends declareConstructor<Cause_.Reason<E["Type"]>, Cause_.Reason<E["Encoded"]>, readonly [E, D], CauseReasonIso<E, D>> {
constructor(_: never);
readonly defect: D;
readonly error: E;
readonly Rebuild: CauseReason<E, D>;
}

Char

interface
Since v3.10.0

Type-level representation of Char.

Signature

interface Char extends String {
constructor(_: never);
readonly Rebuild: Char;
}

Chunk

interface
Since v3.10.0

Type-level representation returned by Chunk.

Signature

interface Chunk<Value extends Constraint> extends declareConstructor<Chunk_.Chunk<Value["Type"]>, Chunk_.Chunk<Value["Encoded"]>, readonly [Value], ChunkIso<Value>> {
constructor(_: never);
readonly Rebuild: Chunk<Value>;
readonly value: Value;
}

Class

interface
Since v3.10.0

Type-level representation returned by Class.

Signature

interface Class<Self, S extends Constraint & {
readonly fields: Struct.Fields;
}, Inherited> extends BottomLazyWithoutNew<SchemaAST.Declaration, decodeTo<declareConstructor<Self, S["Encoded"], readonly [S], S["Iso"]>, S>, readonly [S], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(...args: {} extends S["~type.make.in"] ? [props?: S["~type.make.in"], options?: MakeOptions] : [props: S["~type.make.in"], options?: MakeOptions]);
readonly "~type.make": Self;
readonly "~type.make.in": RequiredKeys<S["~type.make.in"]> extends never ? void | S["~type.make.in"] : S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly fields: S["fields"];
readonly identifier: string;
readonly Iso: S["Iso"];
readonly Type: Self;
extend<Extended = never, Static = {}, Brand = {}>(identifier: string): {
<NewFields extends Fields>(fields: NewFields, annotations?: Declaration<Extended, readonly [Struct<{ [K in string | number | symbol]: { [K in string | number | symbol]: ... & ... extends never ? ... & ... : ... & ...[K] }[K] }>]>): [Extended] extends [never] ? "Missing `Self` generic - use `class Self extends Base.extend<Self>(...)`" : InheritStaticMembers<Class<Extended, Struct<{ [K in string | number | symbol]: { [K in string | number | symbol]: ... & ... extends never ? ... & ... : ... & ...[K] }[K] }>, Self & Brand>, Static>;
<Extension extends Struct<Fields>>(schema: Extension, annotations?: Declaration<Extended, readonly [Struct<{ [K in string | number | symbol]: { [K in string | number | symbol]: ... & ... extends never ? ... & ... : ... & ...[K] }[K] }>]>): [Extended] extends [never] ? "Missing `Self` generic - use `class Self extends Base.extend<Self>(...)`" : InheritStaticMembers<Class<Extended, Struct<{ [K in string | number | symbol]: { [K in string | number | symbol]: ... & ... extends never ? ... & ... : ... & ...[K] }[K] }>, Self & Brand>, Static>;
};
mapFields<To extends Fields>(f: (fields: S["fields"]) => To, options?: {
readonly unsafePreserveChecks?: boolean;
}): Struct<{ [K in string | number | symbol]: Readonly<To>[K] }>;
}

Codec

interface
Since v4.0.0

A schema that tracks the decoded type T, the encoded type E, and the Effect services required during decoding (RD) and encoding (RE).

Details

Use Codec<T, E, RD, RE> when you need to preserve full type information about a schema โ€” both what it decodes to and what it serializes from/to. Most concrete schemas produced by this module implement Codec.

For APIs that only need one direction, prefer the narrower views:

  • Decoder<T, RD> โ€” decode-only
  • Encoder<E, RE> โ€” encode-only
  • Schema<T> โ€” type-only (no encoded representation)

See

Signature

interface Codec<out T, out E = T, out RD = never, out RE = never> extends Schema<T> {
constructor(_: never);
readonly DecodingServices: RD;
readonly Encoded: E;
readonly EncodingServices: RE;
readonly Rebuild: Codec<T, E, RD, RE>;
}

Example

import { Schema } from "effect"
const serialize = <T>(codec: Schema.Codec<T, string>, value: T): string =>
Schema.encodeSync(codec)(value)
serialize(Schema.NumberFromString, 42) // => "42"

Constraint

interface
Since v4.0.0

Lightweight structural constraint for APIs that accept schema values but only read their data and type-level views.

When to use

Use when you need to constrain a generic value to be a schema, but the API only reads properties such as ast, Type, Encoded, service requirements, constructor input views, or modifier flags.

Details

Constraint keeps the schema type identifier and the property surface needed by schema constructors, while avoiding the full Bottom protocol. Use Top when an API calls schema methods such as annotate, check, rebuild, make, or makeEffect.

See

  • Top for the complete schema protocol.

Signature

interface Constraint {
readonly "~effect/Schema/Schema": "~effect/Schema/Schema";
readonly "~encoded.mutability": Mutability;
readonly "~encoded.optionality": Optionality;
readonly "~type.constructor.default": ConstructorDefault;
readonly "~type.make": unknown;
readonly "~type.make.in": unknown;
readonly "~type.mutability": Mutability;
readonly "~type.optionality": Optionality;
readonly "~type.parameters": any;
readonly ast: AST;
readonly DecodingServices: unknown;
readonly Encoded: unknown;
readonly EncodingServices: unknown;
readonly Iso: unknown;
readonly Type: unknown;
}
Since v4.0.0

Lightweight structural constraint for APIs that need codec type views but do not need the full schema protocol.

When to use

Use when you need to preserve decoded type, encoded type, and service requirements for a schema value, but the API does not call schema methods such as annotate, check, rebuild, make, or makeEffect.

See

  • Constraint for the generic lightweight schema constraint.
  • Codec for the full schema protocol with codec type views.

Signature

interface ConstraintCodec<out T, out E = T, out RD = never, out RE = never> extends Constraint {
readonly DecodingServices: RD;
readonly Encoded: E;
readonly EncodingServices: RE;
readonly Type: T;
}
Since v4.0.0

Lightweight structural constraint for APIs that need decoder type views but do not need the full schema protocol.

When to use

Use when you need to preserve a schema's decoded type and decoding services, but the API does not constrain the encoded type, encoding services, or call schema methods such as annotate, check, rebuild, make, or makeEffect.

See

  • ConstraintCodec for APIs that need both decoded and encoded codec views.
  • Codec for the full schema protocol with codec type views.

Signature

interface ConstraintDecoder<out T, out RD = never> extends ConstraintCodec<T, unknown, RD, unknown> {}
Since v4.0.0

Lightweight structural constraint for APIs that need encoder type views but do not need the full schema protocol.

When to use

Use when you need to preserve a schema's encoded type and encoding services, but the API does not constrain the decoded type, decoding services, or call schema methods such as annotate, check, rebuild, make, or makeEffect.

See

  • ConstraintCodec for APIs that need both decoded and encoded codec views.
  • Codec for the full schema protocol with codec type views.

Signature

interface ConstraintEncoder<out E, out RE = never> extends ConstraintCodec<unknown, E, unknown, RE> {}
Since v4.0.0

Lightweight structural constraint for APIs that need schema views and the rebuilt schema type, but do not call the full schema protocol.

When to use

Use when an API needs to read Rebuild in addition to the schema views exposed by Constraint, but does not call methods such as annotate, check, rebuild, make, or makeEffect.

Signature

interface ConstraintRebuildable extends Constraint {
readonly Rebuild: Constraint;
}

Whether a schema field has a constructor default value.

See

  • withConstructorDefault โ€” add a default to a schema field
  • tag โ€” creates a literal field with a constructor default

Signature

type ConstructorDefault = "no-default" | "with-default"

Cookies

interface unstable
Since v4.0.0

Type-level representation of Cookies.

Signature

interface Cookies extends declare<Cookies_.Cookies, Record_.ReadonlyRecord<string, Cookies_.Cookie>> {
constructor(_: never);
readonly Rebuild: Cookies;
}

Date

interface
Since v4.0.0

Type-level representation of Date.

Signature

interface Date extends declare<globalThis.Date> {
constructor(_: never);
readonly Rebuild: Date;
}
Since v4.0.0

Type-level representation of DateFromMillis.

Signature

interface DateFromMillis extends decodeTo<Date, Int> {
constructor(_: never);
readonly Rebuild: DateFromMillis;
}
Since v3.10.0

Type-level representation of DateFromString.

Signature

interface DateFromString extends decodeTo<Date, String> {
constructor(_: never);
readonly Rebuild: DateFromString;
}

DateTimeUtc

interface
Since v3.10.0

Type-level representation of DateTimeUtc.

Signature

interface DateTimeUtc extends declare<DateTime.Utc> {
constructor(_: never);
readonly Rebuild: DateTimeUtc;
}
Since v3.12.0

Type-level representation of DateTimeUtcFromDate.

Signature

interface DateTimeUtcFromDate extends decodeTo<DateTimeUtc, Date> {
constructor(_: never);
readonly Rebuild: DateTimeUtcFromDate;
}
Since v4.0.0

Type-level representation of DateTimeUtcFromMillis.

Signature

interface DateTimeUtcFromMillis extends decodeTo<instanceOf<DateTime.Utc>, Int> {
constructor(_: never);
readonly Rebuild: DateTimeUtcFromMillis;
}
Since v4.0.0

Type-level representation of DateTimeUtcFromString.

Signature

interface DateTimeUtcFromString extends decodeTo<DateTimeUtc, String> {
constructor(_: never);
readonly Rebuild: DateTimeUtcFromString;
}

DateTimeZoned

interface
Since v3.10.0

Type-level representation of DateTimeZoned.

Signature

interface DateTimeZoned extends declare<DateTime.Zoned> {
constructor(_: never);
readonly Rebuild: DateTimeZoned;
}
Since v4.0.0

Type-level representation of DateTimeZonedFromString.

Signature

interface DateTimeZonedFromString extends decodeTo<DateTimeZoned, String> {
constructor(_: never);
readonly Rebuild: DateTimeZonedFromString;
}

Decoder

interface
Since v4.0.0

A schema that tracks the decoded type T and the Effect services required during decoding (RD).

When to use

Use when you need to preserve a schema's decoded type and decoding service requirements, but do not need to constrain its encoded representation or encoding services.

See

  • Codec for preserving both decoded and encoded type information.
  • Encoder for the encode-only view.

Signature

interface Decoder<out T, out RD = never> extends Schema<T> {
constructor(_: never);
readonly DecodingServices: RD;
readonly Encoded: unknown;
readonly EncodingServices: unknown;
readonly Rebuild: Decoder<T, RD>;
}

Defect

interface
Since v3.10.0

Type-level representation of Defect.

Signature

interface Defect extends decodeTo<Unknown, typeof Json> {
constructor(_: never);
readonly Rebuild: Defect;
}

DnsAaaaRecord

interface
Since v4.0.0

Type-level representation of DnsAaaaRecord.

Signature

interface DnsAaaaRecord extends declare<Dns_.Aaaa> {
constructor(_: never);
readonly Rebuild: DnsAaaaRecord;
}

DnsARecord

interface
Since v4.0.0

Type-level representation of DnsARecord.

Signature

interface DnsARecord extends declare<Dns_.A> {
constructor(_: never);
readonly Rebuild: DnsARecord;
}

DnsCaaRecord

interface
Since v4.0.0

Type-level representation of DnsCaaRecord.

Signature

interface DnsCaaRecord extends declare<Dns_.Caa> {
constructor(_: never);
readonly Rebuild: DnsCaaRecord;
}
Since v4.0.0

Type-level representation of DnsCnameRecord.

Signature

interface DnsCnameRecord extends declare<Dns_.Cname> {
constructor(_: never);
readonly Rebuild: DnsCnameRecord;
}

DnsMxRecord

interface
Since v4.0.0

Type-level representation of DnsMxRecord.

Signature

interface DnsMxRecord extends declare<Dns_.Mx> {
constructor(_: never);
readonly Rebuild: DnsMxRecord;
}
Since v4.0.0

Type-level representation of DnsNaptrRecord.

Signature

interface DnsNaptrRecord extends declare<Dns_.Naptr> {
constructor(_: never);
readonly Rebuild: DnsNaptrRecord;
}

DnsNsRecord

interface
Since v4.0.0

Type-level representation of DnsNsRecord.

Signature

interface DnsNsRecord extends declare<Dns_.Ns> {
constructor(_: never);
readonly Rebuild: DnsNsRecord;
}

DnsPtrRecord

interface
Since v4.0.0

Type-level representation of DnsPtrRecord.

Signature

interface DnsPtrRecord extends declare<Dns_.Ptr> {
constructor(_: never);
readonly Rebuild: DnsPtrRecord;
}

DnsRecord

interface
Since v4.0.0

Type-level representation of DnsRecord.

Signature

interface DnsRecord extends Union<readonly [DnsARecord, DnsAaaaRecord, DnsCaaRecord, DnsCnameRecord, DnsMxRecord, DnsNaptrRecord, DnsNsRecord, DnsPtrRecord, DnsSoaRecord, DnsSrvRecord, DnsTlsaRecord, DnsTxtRecord]> {
constructor(_: never);
readonly Rebuild: DnsRecord;
}

DnsRecordType

interface
Since v4.0.0

Type-level representation of DnsRecordType.

Signature

interface DnsRecordType extends Literals<ReadonlyArray<Dns_.RecordType>> {
constructor(_: never);
}

DnsSoaRecord

interface
Since v4.0.0

Type-level representation of DnsSoaRecord.

Signature

interface DnsSoaRecord extends declare<Dns_.Soa> {
constructor(_: never);
readonly Rebuild: DnsSoaRecord;
}

DnsSrvRecord

interface
Since v4.0.0

Type-level representation of DnsSrvRecord.

Signature

interface DnsSrvRecord extends declare<Dns_.Srv> {
constructor(_: never);
readonly Rebuild: DnsSrvRecord;
}

DnsTlsaRecord

interface
Since v4.0.0

Type-level representation of DnsTlsaRecord.

Signature

interface DnsTlsaRecord extends declare<Dns_.Tlsa> {
constructor(_: never);
readonly Rebuild: DnsTlsaRecord;
}

DnsTxtRecord

interface
Since v4.0.0

Type-level representation of DnsTxtRecord.

Signature

interface DnsTxtRecord extends declare<Dns_.Txt> {
constructor(_: never);
readonly Rebuild: DnsTxtRecord;
}

DomainName

interface
Since v4.0.0

Type-level representation of DomainName.

Signature

interface DomainName extends brand<String, "~effect/net/Host/DomainName"> {
constructor(_: never);
readonly Rebuild: DomainName;
}
Since v4.0.0

Type-level representation of DomainNameFromString.

Signature

interface DomainNameFromString extends decodeTo<DomainName, String> {
constructor(_: never);
readonly Rebuild: DomainNameFromString;
}

Duration

interface
Since v3.10.0

Type-level representation of Duration.

Signature

interface Duration extends declare<Duration_.Duration> {
constructor(_: never);
readonly Rebuild: Duration;
}
Since v3.10.0

Type-level representation of DurationFromMillis.

Signature

interface DurationFromMillis extends decodeTo<Duration, Number> {
constructor(_: never);
readonly Rebuild: DurationFromMillis;
}
Since v3.10.0

Type-level representation of DurationFromNanos.

Signature

interface DurationFromNanos extends decodeTo<Duration, BigInt> {
constructor(_: never);
readonly Rebuild: DurationFromNanos;
}
Since v4.0.0

Type-level representation of DurationFromString.

Signature

interface DurationFromString extends decodeTo<Duration, String> {
constructor(_: never);
readonly Rebuild: DurationFromString;
}

EncodedGraph

type unstable
Since v4.0.0

Encoded representation of an immutable Effect graph.

Signature

type EncodedGraph<N, E, T extends Graph_.Kind> = Graph_.Snapshot<N, E, T>

Encoder

interface
Since v4.0.0

A schema that tracks the encoded type E and the Effect services required during encoding (RE).

When to use

Use when you need to preserve a schema's encoded type and encoding service requirements, but do not need to constrain its decoded representation or decoding services.

See

  • Codec for preserving both decoded and encoded type information.
  • Decoder for the decode-only view.

Signature

interface Encoder<out E, out RE = never> extends Schema<unknown> {
constructor(_: never);
readonly DecodingServices: unknown;
readonly Encoded: E;
readonly EncodingServices: RE;
readonly Rebuild: Encoder<E, RE>;
}

Enum

interface
Since v4.0.0

Type-level representation returned by Enum.

Signature

interface Enum<A extends {
[x: string]: string | number;
}> extends Bottom<A[keyof A], A[keyof A], never, never, SchemaAST.Enum, Enum<A>> {
constructor(_: never);
readonly enums: A;
}

ErrorInstance

interface
Since v4.0.0

Type-level representation of ErrorInstance.

Signature

interface ErrorInstance extends instanceOf<globalThis.Error> {
constructor(_: never);
readonly Rebuild: ErrorInstance;
}

Exit

interface
Since v3.10.0

Type-level representation returned by Exit.

Signature

interface Exit<A extends Constraint, E extends Constraint, D extends Constraint> extends declareConstructor<Exit_.Exit<A["Type"], E["Type"]>, Exit_.Exit<A["Encoded"], E["Encoded"]>, readonly [A, E, D], ExitIso<A, E, D>> {
constructor(_: never);
readonly defect: D;
readonly error: E;
readonly Rebuild: Exit<A, E, D>;
readonly value: A;
}

File

interface
Since v4.0.0

Type-level representation of File.

Signature

interface File extends instanceOf<globalThis.File> {
constructor(_: never);
readonly Rebuild: File;
}
Since v3.10.0

A single failure reported by a filter predicate. Used as the element type of the array arm of FilterOutput, and also accepted on its own.

Details

  • string: failure with that string as the message. Produces an SchemaIssue.InvalidValue with the string used as the issue's message annotation and honors reportInput.
  • SchemaIssue.Issue: a fully-formed issue, returned as-is. It is not enriched when reportInput is enabled.
  • { path, issue }: failure attached to a nested path. issue is either a string (wrapped in an SchemaIssue.InvalidValue that honors reportInput) or a full SchemaIssue.Issue (returned unchanged); the result is wrapped in an SchemaIssue.Pointer at the given path.

Signature

type FilterIssue = string | SchemaIssue.Issue | {
readonly issue: string | SchemaIssue.Issue;
readonly path: ReadonlyArray<PropertyKey>;
}
Since v3.10.0

The value a filter predicate (see makeFilter) may return.

Details

Each shape is normalized into an SchemaIssue.Issue (or undefined for success) before being attached to the parse result:

  • undefined: success. The input satisfies the filter.
  • true: success. Equivalent to undefined, useful when the predicate is a plain boolean expression.
  • false: generic failure. Produces an SchemaIssue.InvalidValue with no custom message and honors reportInput.
  • FilterIssue: a single failure. See FilterIssue for the shapes (string, SchemaIssue.Issue, or { path, issue }).
  • ReadonlyArray<FilterIssue>: several failures reported together. An empty array is treated as success; a single-element array is equivalent to returning that element directly; otherwise the entries are grouped into an SchemaIssue.Composite.

Signature

type FilterOutput = undefined | boolean | FilterIssue | ReadonlyArray<FilterIssue>

Finite

interface
Since v3.10.0

Type-level representation of Finite.

Signature

interface Finite extends Number {
constructor(_: never);
readonly Rebuild: Finite;
}
Since v4.0.0

Type-level representation of FiniteFromString.

Signature

interface FiniteFromString extends decodeTo<Finite, String> {
constructor(_: never);
readonly Rebuild: FiniteFromString;
}

FormData

interface
Since v4.0.0

Type-level representation of FormData.

Signature

interface FormData extends instanceOf<globalThis.FormData> {
constructor(_: never);
readonly Rebuild: FormData;
}

fromFormData

interface
Since v4.0.0

Type-level representation returned by fromFormData.

Signature

interface fromFormData<S extends Constraint> extends decodeTo<S, FormData> {
constructor(_: never);
readonly Rebuild: fromFormData<S>;
}
Since v4.0.0

Type-level representation returned by fromJsonString.

Signature

interface fromJsonString<S extends Constraint> extends decodeTo<S, String> {
constructor(_: never);
readonly Rebuild: fromJsonString<S>;
}
Since v4.0.0

Type-level representation returned by fromURLSearchParams.

Signature

interface fromURLSearchParams<S extends Constraint> extends decodeTo<S, URLSearchParams> {
constructor(_: never);
readonly Rebuild: fromURLSearchParams<S>;
}

Graph

interface unstable
Since v4.0.0

Type-level representation returned by Graph.

Signature

interface Graph<T extends Graph_.Kind, Node extends Constraint, Edge extends Constraint> extends declareConstructor<Graph_.Graph<Node["Type"], Edge["Type"], T>, Graph_.Graph<Node["Encoded"], Edge["Encoded"], T>, readonly [Node, Edge], GraphIso<T, Node, Edge>> {
constructor(_: never);
readonly edge: Edge;
readonly node: Node;
readonly Rebuild: Graph<T, Node, Edge>;
readonly type: T;
}

HashMap

interface
Since v3.10.0

Type-level representation returned by HashMap.

Signature

interface HashMap<Key extends Constraint, Value extends Constraint> extends declareConstructor<HashMap_.HashMap<Key["Type"], Value["Type"]>, HashMap_.HashMap<Key["Encoded"], Value["Encoded"]>, readonly [Key, Value], HashMapIso<Key, Value>> {
constructor(_: never);
readonly key: Key;
readonly Rebuild: HashMap<Key, Value>;
readonly value: Value;
}

HashSet

interface
Since v3.10.0

Type-level representation returned by HashSet.

Signature

interface HashSet<Value extends Constraint> extends declareConstructor<HashSet_.HashSet<Value["Type"]>, HashSet_.HashSet<Value["Encoded"]>, readonly [Value], HashSetIso<Value>> {
constructor(_: never);
readonly Rebuild: HashSet<Value>;
readonly value: Value;
}

Headers

interface unstable
Since v4.0.0

Type-level representation of Headers.

Signature

interface Headers extends declare<Headers_.Headers, {
[x: string]: string;
}> {
constructor(_: never);
readonly Rebuild: Headers;
}

Host

interface
Since v4.0.0

Type-level representation of Host.

Signature

interface Host extends Union<readonly [IpAddress, ScopedIpv6Literal, DomainName]> {
constructor(_: never);
readonly Rebuild: Host;
}
Since v4.0.0

Type-level representation of HostFromString.

Signature

interface HostFromString extends Union<readonly [IpAddressFromString, ScopedIpv6LiteralFromString, DomainNameFromString]> {
constructor(_: never);
readonly Rebuild: HostFromString;
}

HostPort

interface
Since v4.0.0

Type-level representation of HostPort.

Signature

interface HostPort extends declare<Host_.HostPort> {
constructor(_: never);
readonly Rebuild: HostPort;
}
Since v4.0.0

Type-level representation of HostPortFromString.

Signature

interface HostPortFromString extends decodeTo<HostPort, String> {
constructor(_: never);
readonly Rebuild: HostPortFromString;
}

InetAddress

interface unstable
Since v4.0.0

Type-level representation of InetAddress.

Signature

interface InetAddress extends declare<NetAddress_.InetAddress> {
constructor(_: never);
readonly Rebuild: InetAddress;
}

InetAddressFromString

interface unstable
Since v4.0.0

Type-level representation of InetAddressFromString.

Signature

interface InetAddressFromString extends decodeTo<InetAddress, String> {
constructor(_: never);
readonly Rebuild: InetAddressFromString;
}

InetAddressV4

interface unstable
Since v4.0.0

Type-level representation of InetAddressV4.

Signature

interface InetAddressV4 extends declare<NetAddress_.InetAddressV4> {
constructor(_: never);
readonly Rebuild: InetAddressV4;
}

InetAddressV6

interface unstable
Since v4.0.0

Type-level representation of InetAddressV6.

Signature

interface InetAddressV6 extends declare<NetAddress_.InetAddressV6> {
constructor(_: never);
readonly Rebuild: InetAddressV6;
}

instanceOf

interface
Since v3.10.0

Type-level representation returned by instanceOf.

Signature

interface instanceOf<T, Iso = T> extends declare<T, Iso> {
constructor(_: never);
readonly Rebuild: instanceOf<T, Iso>;
}

Int

interface
Since v3.10.0

Type-level representation of Int.

Signature

interface Int extends Number {
constructor(_: never);
readonly Rebuild: Int;
}

IpAddress

interface unstable
Since v4.0.0

Type-level representation of IpAddress.

Signature

interface IpAddress extends declare<NetAddress_.IpAddress> {
constructor(_: never);
readonly Rebuild: IpAddress;
}

IpAddressFromString

interface unstable
Since v4.0.0

Type-level representation of IpAddressFromString.

Signature

interface IpAddressFromString extends decodeTo<IpAddress, String> {
constructor(_: never);
readonly Rebuild: IpAddressFromString;
}

IpInterface

interface unstable
Since v4.0.0

Type-level representation of IpInterface.

Signature

interface IpInterface extends declare<IpInterface_.IpInterface> {
constructor(_: never);
readonly Rebuild: IpInterface;
}

IpInterfaceFromString

interface unstable
Since v4.0.0

Type-level representation of IpInterfaceFromString.

Signature

interface IpInterfaceFromString extends decodeTo<IpInterface, String> {
constructor(_: never);
readonly Rebuild: IpInterfaceFromString;
}

IpLinkLocalAddress

interface unstable
Since v4.0.0

Type-level representation of IpLinkLocalAddress.

Signature

interface IpLinkLocalAddress extends refine<NetAddress_.LinkLocalAddress<NetAddress_.IpAddress>, IpAddress> {
constructor(_: never);
readonly Rebuild: IpLinkLocalAddress;
}
Since v4.0.0

Type-level representation of IpLinkLocalAddressFromString.

Signature

interface IpLinkLocalAddressFromString extends refine<NetAddress_.LinkLocalAddress<NetAddress_.IpAddress>, IpAddressFromString> {
constructor(_: never);
readonly Rebuild: IpLinkLocalAddressFromString;
}

IpLoopbackAddress

interface unstable
Since v4.0.0

Type-level representation of IpLoopbackAddress.

Signature

interface IpLoopbackAddress extends refine<NetAddress_.LoopbackAddress<NetAddress_.IpAddress>, IpAddress> {
constructor(_: never);
readonly Rebuild: IpLoopbackAddress;
}
Since v4.0.0

Type-level representation of IpLoopbackAddressFromString.

Signature

interface IpLoopbackAddressFromString extends refine<NetAddress_.LoopbackAddress<NetAddress_.IpAddress>, IpAddressFromString> {
constructor(_: never);
readonly Rebuild: IpLoopbackAddressFromString;
}

IpMulticastAddress

interface unstable
Since v4.0.0

Type-level representation of IpMulticastAddress.

Signature

interface IpMulticastAddress extends refine<NetAddress_.MulticastAddress<NetAddress_.IpAddress>, IpAddress> {
constructor(_: never);
readonly Rebuild: IpMulticastAddress;
}
Since v4.0.0

Type-level representation of IpMulticastAddressFromString.

Signature

interface IpMulticastAddressFromString extends refine<NetAddress_.MulticastAddress<NetAddress_.IpAddress>, IpAddressFromString> {
constructor(_: never);
readonly Rebuild: IpMulticastAddressFromString;
}

IpNetwork

interface unstable
Since v4.0.0

Type-level representation of IpNetwork.

Signature

interface IpNetwork extends declare<IpNetwork_.IpNetwork> {
constructor(_: never);
readonly Rebuild: IpNetwork;
}

IpNetworkFromString

interface unstable
Since v4.0.0

Type-level representation of IpNetworkFromString.

Signature

interface IpNetworkFromString extends decodeTo<IpNetwork, String> {
constructor(_: never);
readonly Rebuild: IpNetworkFromString;
}

IpUnicastAddress

interface unstable
Since v4.0.0

Type-level representation of IpUnicastAddress.

Signature

interface IpUnicastAddress extends refine<NetAddress_.UnicastAddress<NetAddress_.IpAddress>, IpAddress> {
constructor(_: never);
readonly Rebuild: IpUnicastAddress;
}

IpUnicastAddressFromString

interface unstable
Since v4.0.0

Type-level representation of IpUnicastAddressFromString.

Signature

interface IpUnicastAddressFromString extends refine<NetAddress_.UnicastAddress<NetAddress_.IpAddress>, IpAddressFromString> {
constructor(_: never);
readonly Rebuild: IpUnicastAddressFromString;
}

IpUnspecifiedAddress

interface unstable
Since v4.0.0

Type-level representation of IpUnspecifiedAddress.

Signature

interface IpUnspecifiedAddress extends refine<NetAddress_.UnspecifiedAddress<NetAddress_.IpAddress>, IpAddress> {
constructor(_: never);
readonly Rebuild: IpUnspecifiedAddress;
}
Since v4.0.0

Type-level representation of IpUnspecifiedAddressFromString.

Signature

interface IpUnspecifiedAddressFromString extends refine<NetAddress_.UnspecifiedAddress<NetAddress_.IpAddress>, IpAddressFromString> {
constructor(_: never);
readonly Rebuild: IpUnspecifiedAddressFromString;
}

Ipv4Address

interface unstable
Since v4.0.0

Type-level representation of Ipv4Address.

Signature

interface Ipv4Address extends declare<NetAddress_.Ipv4Address> {
constructor(_: never);
readonly Rebuild: Ipv4Address;
}

Ipv4AddressFromString

interface unstable
Since v4.0.0

Type-level representation of Ipv4AddressFromString.

Signature

interface Ipv4AddressFromString extends decodeTo<Ipv4Address, String> {
constructor(_: never);
readonly Rebuild: Ipv4AddressFromString;
}

Ipv4BroadcastAddress

interface unstable
Since v4.0.0

Type-level representation of Ipv4BroadcastAddress.

Signature

interface Ipv4BroadcastAddress extends refine<NetAddress_.BroadcastAddress<NetAddress_.Ipv4Address>, Ipv4Address> {
constructor(_: never);
readonly Rebuild: Ipv4BroadcastAddress;
}
Since v4.0.0

Type-level representation of Ipv4BroadcastAddressFromString.

Signature

interface Ipv4BroadcastAddressFromString extends refine<NetAddress_.BroadcastAddress<NetAddress_.Ipv4Address>, Ipv4AddressFromString> {
constructor(_: never);
readonly Rebuild: Ipv4BroadcastAddressFromString;
}

Ipv4Interface

interface unstable
Since v4.0.0

Type-level representation of Ipv4Interface.

Signature

interface Ipv4Interface extends declare<IpInterface_.Ipv4Interface> {
constructor(_: never);
readonly Rebuild: Ipv4Interface;
}

Ipv4InterfaceFromString

interface unstable
Since v4.0.0

Type-level representation of Ipv4InterfaceFromString.

Signature

interface Ipv4InterfaceFromString extends decodeTo<Ipv4Interface, String> {
constructor(_: never);
readonly Rebuild: Ipv4InterfaceFromString;
}

Ipv4Network

interface unstable
Since v4.0.0

Type-level representation of Ipv4Network.

Signature

interface Ipv4Network extends declare<IpNetwork_.Ipv4Network> {
constructor(_: never);
readonly Rebuild: Ipv4Network;
}

Ipv4NetworkFromString

interface unstable
Since v4.0.0

Type-level representation of Ipv4NetworkFromString.

Signature

interface Ipv4NetworkFromString extends decodeTo<Ipv4Network, String> {
constructor(_: never);
readonly Rebuild: Ipv4NetworkFromString;
}

Ipv4PrivateAddress

interface unstable
Since v4.0.0

Type-level representation of Ipv4PrivateAddress.

Signature

interface Ipv4PrivateAddress extends refine<NetAddress_.PrivateAddress<NetAddress_.Ipv4Address>, Ipv4Address> {
constructor(_: never);
readonly Rebuild: Ipv4PrivateAddress;
}
Since v4.0.0

Type-level representation of Ipv4PrivateAddressFromString.

Signature

interface Ipv4PrivateAddressFromString extends refine<NetAddress_.PrivateAddress<NetAddress_.Ipv4Address>, Ipv4AddressFromString> {
constructor(_: never);
readonly Rebuild: Ipv4PrivateAddressFromString;
}

Ipv6Address

interface unstable
Since v4.0.0

Type-level representation of Ipv6Address.

Signature

interface Ipv6Address extends declare<NetAddress_.Ipv6Address> {
constructor(_: never);
readonly Rebuild: Ipv6Address;
}

Ipv6AddressFromString

interface unstable
Since v4.0.0

Type-level representation of Ipv6AddressFromString.

Signature

interface Ipv6AddressFromString extends decodeTo<Ipv6Address, String> {
constructor(_: never);
readonly Rebuild: Ipv6AddressFromString;
}

Ipv6Interface

interface unstable
Since v4.0.0

Type-level representation of Ipv6Interface.

Signature

interface Ipv6Interface extends declare<IpInterface_.Ipv6Interface> {
constructor(_: never);
readonly Rebuild: Ipv6Interface;
}

Ipv6InterfaceFromString

interface unstable
Since v4.0.0

Type-level representation of Ipv6InterfaceFromString.

Signature

interface Ipv6InterfaceFromString extends decodeTo<Ipv6Interface, String> {
constructor(_: never);
readonly Rebuild: Ipv6InterfaceFromString;
}

Ipv6Network

interface unstable
Since v4.0.0

Type-level representation of Ipv6Network.

Signature

interface Ipv6Network extends declare<IpNetwork_.Ipv6Network> {
constructor(_: never);
readonly Rebuild: Ipv6Network;
}

Ipv6NetworkFromString

interface unstable
Since v4.0.0

Type-level representation of Ipv6NetworkFromString.

Signature

interface Ipv6NetworkFromString extends decodeTo<Ipv6Network, String> {
constructor(_: never);
readonly Rebuild: Ipv6NetworkFromString;
}

Ipv6UniqueLocalAddress

interface unstable
Since v4.0.0

Type-level representation of Ipv6UniqueLocalAddress.

Signature

interface Ipv6UniqueLocalAddress extends refine<NetAddress_.UniqueLocalAddress<NetAddress_.Ipv6Address>, Ipv6Address> {
constructor(_: never);
readonly Rebuild: Ipv6UniqueLocalAddress;
}
Since v4.0.0

Type-level representation of Ipv6UniqueLocalAddressFromString.

Signature

interface Ipv6UniqueLocalAddressFromString extends refine<NetAddress_.UniqueLocalAddress<NetAddress_.Ipv6Address>, Ipv6AddressFromString> {
constructor(_: never);
readonly Rebuild: Ipv6UniqueLocalAddressFromString;
}

Json

type
Since v4.0.0

Recursive TypeScript type for any valid immutable JSON value: null, number, boolean, string, a readonly array of Json values, or a readonly record of string โ†’ Json. For the corresponding schema, see the Json const.

Signature

type Json = null | number | boolean | string | JsonArray | JsonObject

JsonArray

interface
Since v4.0.0

A readonly array of Json values.

Signature

interface JsonArray extends ReadonlyArray<Json> {
[n: number]: Json;
}

JsonFromUrlParamsField

interface unstable
Since v4.0.0

Type-level representation of JsonFromUrlParamsField.

Signature

interface JsonFromUrlParamsField extends decodeTo<fromJsonString<Unknown>, UrlParams> {
constructor(_: never);
readonly Rebuild: JsonFromUrlParamsField;
}

JsonObject

interface
Since v4.0.0

A readonly record whose values are Json values.

Signature

interface JsonObject {
[x: string]: Json;
}

Literal

interface
Since v3.10.0

Type-level representation returned by Literal.

Signature

interface Literal<L extends SchemaAST.LiteralValue> extends Bottom<L, L, never, never, SchemaAST.Literal, Literal<L>> {
constructor(_: never);
readonly literal: L;
transform<L2 extends LiteralValue>(to: L2): decodeTo<Literal<L2>, Literal<L>>;
}

Literals

interface
Since v4.0.0

Type-level representation returned by Literals.

Signature

interface Literals<L extends ReadonlyArray<SchemaAST.LiteralValue>> extends Bottom<L[number], L[number], never, never, SchemaAST.Union<SchemaAST.Literal>, Literals<L>> {
constructor(_: never);
readonly literals: L;
readonly members: { [K in string | number | symbol]: Literal<L[K]> };
mapMembers<To extends readonly Array<Constraint>>(f: (members: { [K in string | number | symbol]: Literal<L[K]> }) => To): Union<{ [K in string | number | symbol]: Readonly<To>[K] }>;
pick<L2 extends readonly Array<L[number]>>(literals: L2): Literals<L2>;
transform<L2 extends { [I in string | number | symbol]: LiteralValue }>(to: L2): Union<{ [I in string | number | symbol]: decodeTo<Literal<L2[I]>, Literal<L[I]>, never, never> }>;
}

MacAddress

interface unstable
Since v4.0.0

Type-level representation of MacAddress.

Signature

interface MacAddress extends declare<NetAddress_.MacAddress> {
constructor(_: never);
readonly Rebuild: MacAddress;
}

MacAddressFromString

interface unstable
Since v4.0.0

Type-level representation of MacAddressFromString.

Signature

interface MacAddressFromString extends decodeTo<MacAddress, String> {
constructor(_: never);
readonly Rebuild: MacAddressFromString;
}

MacBroadcastAddress

interface unstable
Since v4.0.0

Type-level representation of MacBroadcastAddress.

Signature

interface MacBroadcastAddress extends refine<NetAddress_.BroadcastAddress<NetAddress_.MacAddress>, MacAddress> {
constructor(_: never);
readonly Rebuild: MacBroadcastAddress;
}
Since v4.0.0

Type-level representation of MacBroadcastAddressFromString.

Signature

interface MacBroadcastAddressFromString extends refine<NetAddress_.BroadcastAddress<NetAddress_.MacAddress>, MacAddressFromString> {
constructor(_: never);
readonly Rebuild: MacBroadcastAddressFromString;
}
Since v4.0.0

Type-level representation of MacLocallyAdministeredAddress.

Signature

interface MacLocallyAdministeredAddress extends refine<NetAddress_.LocallyAdministeredAddress<NetAddress_.MacAddress>, MacAddress> {
constructor(_: never);
readonly Rebuild: MacLocallyAdministeredAddress;
}

Type-level representation of MacLocallyAdministeredAddressFromString.

Signature

interface MacLocallyAdministeredAddressFromString extends refine<NetAddress_.LocallyAdministeredAddress<NetAddress_.MacAddress>, MacAddressFromString> {
constructor(_: never);
readonly Rebuild: MacLocallyAdministeredAddressFromString;
}

MacMulticastAddress

interface unstable
Since v4.0.0

Type-level representation of MacMulticastAddress.

Signature

interface MacMulticastAddress extends refine<NetAddress_.MulticastAddress<NetAddress_.MacAddress>, MacAddress> {
constructor(_: never);
readonly Rebuild: MacMulticastAddress;
}
Since v4.0.0

Type-level representation of MacMulticastAddressFromString.

Signature

interface MacMulticastAddressFromString extends refine<NetAddress_.MulticastAddress<NetAddress_.MacAddress>, MacAddressFromString> {
constructor(_: never);
readonly Rebuild: MacMulticastAddressFromString;
}

MacUnicastAddress

interface unstable
Since v4.0.0

Type-level representation of MacUnicastAddress.

Signature

interface MacUnicastAddress extends refine<NetAddress_.UnicastAddress<NetAddress_.MacAddress>, MacAddress> {
constructor(_: never);
readonly Rebuild: MacUnicastAddress;
}
Since v4.0.0

Type-level representation of MacUnicastAddressFromString.

Signature

interface MacUnicastAddressFromString extends refine<NetAddress_.UnicastAddress<NetAddress_.MacAddress>, MacAddressFromString> {
constructor(_: never);
readonly Rebuild: MacUnicastAddressFromString;
}
Since v4.0.0

Type-level representation of MacUniversallyAdministeredAddress.

Signature

interface MacUniversallyAdministeredAddress extends refine<NetAddress_.UniversallyAdministeredAddress<NetAddress_.MacAddress>, MacAddress> {
constructor(_: never);
readonly Rebuild: MacUniversallyAdministeredAddress;
}

Type-level representation of MacUniversallyAdministeredAddressFromString.

Signature

interface MacUniversallyAdministeredAddressFromString extends refine<NetAddress_.UniversallyAdministeredAddress<NetAddress_.MacAddress>, MacAddressFromString> {
constructor(_: never);
readonly Rebuild: MacUniversallyAdministeredAddressFromString;
}
Since v4.0.0

Whether a schema field is readonly or mutable within a struct.

See

  • mutableKey โ€” mark a struct field as mutable

Signature

type Mutability = "readonly" | "mutable"
Since v4.0.0

Recursive TypeScript type for mutable JSON values: null, number, boolean, string, mutable arrays, or mutable string-keyed records.

Signature

type MutableJson = null | number | boolean | string | MutableJsonArray | MutableJsonObject
Since v4.0.0

A mutable array of MutableJson values.

Signature

interface MutableJsonArray extends Array<MutableJson> {
[n: number]: MutableJson;
}
Since v4.0.0

A mutable record whose values are MutableJson values.

Signature

interface MutableJsonObject {
[x: string]: MutableJson;
}

mutableKey

interface
Since v4.0.0

Type-level representation returned by mutableKey.

Signature

interface mutableKey<S extends Constraint> extends BottomLazy<S["ast"], mutableKey<S>, S["~type.parameters"], "mutable", S["~type.optionality"], S["~type.constructor.default"], "mutable", S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly schema: S;
readonly Type: S["Type"];
}

Natural

interface
Since v4.0.0

Type-level representation of Natural.

Signature

interface Natural extends Int {
constructor(_: never);
readonly Rebuild: Natural;
}

Never

interface
Since v3.10.0

Type-level representation of Never.

Signature

interface Never extends Bottom<never, never, never, never, SchemaAST.Never, Never> {
constructor(_: never);
}

NonEmptyArray

interface
Since v3.10.0

Type-level representation returned by NonEmptyArray.

Signature

interface NonEmptyArray<S extends Constraint> extends BottomLazy<SchemaAST.Arrays, NonEmptyArray<S>> {
constructor(_: never);
readonly "~type.make": readonly [S["~type.make"], S["~type.make"]];
readonly "~type.make.in": readonly [S["~type.make"], S["~type.make"]];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: readonly [S["Encoded"], S["Encoded"]];
readonly EncodingServices: S["EncodingServices"];
readonly Iso: readonly [S["Iso"], S["Iso"]];
readonly Type: readonly [S["Type"], S["Type"]];
readonly value: S;
}
Since v3.10.0

Type-level representation of NonEmptyString.

Signature

interface NonEmptyString extends String {
constructor(_: never);
readonly Rebuild: NonEmptyString;
}

Null

interface
Since v3.10.0

Type-level representation of Null.

Signature

interface Null extends Bottom<null, null, never, never, SchemaAST.Null, Null> {
constructor(_: never);
}

NullishOr

interface
Since v3.10.0

Type-level representation returned by NullishOr.

Signature

interface NullishOr<S extends Constraint> extends Union<readonly [S, Null, Undefined]> {
constructor(_: never);
readonly Rebuild: NullishOr<S>;
}

NullOr

interface
Since v3.10.0

Type-level representation returned by NullOr.

Signature

interface NullOr<S extends Constraint> extends Union<readonly [S, Null]> {
constructor(_: never);
readonly Rebuild: NullOr<S>;
}

Number

interface
Since v4.0.0

Type-level representation of Number.

Signature

interface Number extends Bottom<number, number, never, never, SchemaAST.Number, Number> {
constructor(_: never);
}
Since v3.10.0

Type-level representation of NumberFromString.

Signature

interface NumberFromString extends decodeTo<Number, String> {
constructor(_: never);
readonly Rebuild: NumberFromString;
}

ObjectKeyword

interface
Since v4.0.0

Type-level representation of ObjectKeyword.

Signature

interface ObjectKeyword extends Bottom<object, object, never, never, SchemaAST.ObjectKeyword, ObjectKeyword> {
constructor(_: never);
}

Opaque

interface
Since v4.0.0

Type-level representation returned by Opaque.

Signature

interface Opaque<Self, S extends Top, Brand> extends BottomLazyWithoutNew<S["ast"], S["Rebuild"], S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly Type: Self;
}

Optic

interface
Since v4.0.0

A schema that additionally supports optic (lens/prism) operations.

Details

Optic<T, Iso> extends Schema<T> with an Iso type that describes the isomorphic counterpart used by the optic layer. Crucially, decoding and encoding require no Effect services (DecodingServices and EncodingServices are both never), which means the optic can operate purely without an Effect runtime.

Most primitive schemas (e.g. Schema.String, Schema.Number) implement Optic automatically. You normally interact with this interface through Optic_ utilities rather than constructing it directly.

Signature

interface Optic<out T, out Iso> extends Schema<T> {
constructor(_: never);
readonly DecodingServices: never;
readonly EncodingServices: never;
Iso: Iso;
readonly Rebuild: Optic<T, Iso>;
}

Option

interface
Since v3.10.0

Type-level representation returned by Option.

Signature

interface Option<A extends Constraint> extends declareConstructor<Option_.Option<A["Type"]>, Option_.Option<A["Encoded"]>, readonly [A], OptionIso<A>> {
constructor(_: never);
readonly Rebuild: Option<A>;
readonly value: A;
}

optional

interface
Since v3.10.0

Type-level representation returned by optional.

Signature

interface optional<S extends Constraint> extends optionalKey<UndefinedOr<S>> {
constructor(_: never);
readonly Rebuild: optional<S>;
}
Since v4.0.0

Whether a schema field is required or optional within a struct.

See

  • optionalKey โ€” mark a struct field as optional
  • optional โ€” mark a struct field as optional with | undefined

Signature

type Optionality = "required" | "optional"

optionalKey

interface
Since v4.0.0

Type-level representation returned by optionalKey.

Signature

interface optionalKey<S extends Constraint> extends BottomLazy<S["ast"], optionalKey<S>, S["~type.parameters"], S["~type.mutability"], "optional", S["~type.constructor.default"], S["~encoded.mutability"], "optional"> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly schema: S;
readonly Type: S["Type"];
}
Since v3.10.0

Type-level representation returned by OptionFromNullishOr.

Signature

interface OptionFromNullishOr<S extends Constraint> extends decodeTo<Option<toType<S>>, NullishOr<S>> {
constructor(_: never);
readonly Rebuild: OptionFromNullishOr<S>;
}
Since v3.10.0

Type-level representation returned by OptionFromNullOr.

Signature

interface OptionFromNullOr<S extends Constraint> extends decodeTo<Option<toType<S>>, NullOr<S>> {
constructor(_: never);
readonly Rebuild: OptionFromNullOr<S>;
}
Since v4.0.0

Type-level representation returned by OptionFromOptional.

Signature

interface OptionFromOptional<S extends Constraint> extends decodeTo<Option<toType<S>>, optional<S>> {
constructor(_: never);
readonly Rebuild: OptionFromOptional<S>;
}
Since v4.0.0

Type-level representation returned by OptionFromOptionalKey.

Signature

interface OptionFromOptionalKey<S extends Constraint> extends decodeTo<Option<toType<S>>, optionalKey<S>> {
constructor(_: never);
readonly Rebuild: OptionFromOptionalKey<S>;
}

Type-level representation returned by OptionFromOptionalNullOr.

Signature

interface OptionFromOptionalNullOr<S extends Constraint> extends decodeTo<Option<toType<S>>, optional<NullOr<S>>> {
constructor(_: never);
readonly Rebuild: OptionFromOptionalNullOr<S>;
}
Since v3.10.0

Type-level representation returned by OptionFromUndefinedOr.

Signature

interface OptionFromUndefinedOr<S extends Constraint> extends decodeTo<Option<toType<S>>, UndefinedOr<S>> {
constructor(_: never);
readonly Rebuild: OptionFromUndefinedOr<S>;
}

Port

interface
Since v4.0.0

Type-level representation of Port.

Signature

interface Port extends Int {
constructor(_: never);
readonly Rebuild: Port;
}

RecordFromCookies

interface unstable
Since v4.0.0

Type-level representation of RecordFromCookies.

Signature

interface RecordFromCookies extends decodeTo<$Record<String, String>, Cookies> {
constructor(_: never);
readonly Rebuild: RecordFromCookies;
}

RecordFromUrlParams

interface unstable
Since v4.0.0

Type-level representation of RecordFromUrlParams.

Signature

interface RecordFromUrlParams extends decodeTo<$Record<String, Union<readonly [String, NonEmptyArray<String>]>>, UrlParams, never, never> {
constructor(_: never);
readonly Rebuild: RecordFromUrlParams;
}

Redacted

interface
Since v3.10.0

Type-level representation returned by Redacted.

Signature

interface Redacted<S extends Constraint> extends declareConstructor<Redacted_.Redacted<S["Type"]>, Redacted_.Redacted<S["Encoded"]>, readonly [S]> {
constructor(_: never);
readonly Rebuild: Redacted<S>;
readonly value: S;
}
Since v4.0.0

Type-level representation returned by RedactedFromValue.

Signature

interface RedactedFromValue<S extends Constraint> extends decodeTo<Redacted<toType<S>>, S> {
constructor(_: never);
readonly Rebuild: RedactedFromValue<S>;
}

RegExp

interface
Since v4.0.0

Type-level representation of RegExp.

Signature

interface RegExp extends instanceOf<globalThis.RegExp> {
constructor(_: never);
readonly Rebuild: RegExp;
}

Result

interface
Since v4.0.0

Type-level representation returned by Result.

Signature

interface Result<A extends Constraint, E extends Constraint> extends declareConstructor<Result_.Result<A["Type"], E["Type"]>, Result_.Result<A["Encoded"], E["Encoded"]>, readonly [A, E], ResultIso<A, E>> {
constructor(_: never);
readonly failure: E;
readonly Rebuild: Result<A, E>;
readonly success: A;
}

Schema

interface
Since v3.10.0

A typed view of a schema that tracks only the decoded (output) type T.

Details

Use Schema<T> as a constraint when you want to accept "any schema that decodes to T" and do not need to know or constrain the encoded representation, required services, or any other type parameters.

This is a structural interface โ€” concrete schema values are produced by the constructors in this module (e.g. Struct, String, Number). When you also need the encoded type or service requirements, use Codec.

See

  • Codec โ€” also tracks Encoded, DecodingServices, EncodingServices
  • Schema.Type โ€” extract the decoded type at the type level

Signature

interface Schema<out T> extends Top {
constructor(_: never);
readonly Rebuild: Schema<T>;
readonly Type: T;
}

Example

import { Schema } from "effect"
const accept = (_schema: Schema.Schema<string>): void => {}
accept(Schema.String)
accept(Schema.NonEmptyString)
Since v4.0.0

Type-level representation of ScopedIpv6Literal.

Signature

interface ScopedIpv6Literal extends brand<String, "~effect/net/NetAddress/ScopedIpv6Literal"> {
constructor(_: never);
readonly Rebuild: ScopedIpv6Literal;
}

Type-level representation of ScopedIpv6LiteralFromString.

Signature

interface ScopedIpv6LiteralFromString extends decodeTo<ScopedIpv6Literal, String> {
constructor(_: never);
readonly Rebuild: ScopedIpv6LiteralFromString;
}

SocketAddress

interface unstable
Since v4.0.0

Type-level representation of SocketAddress.

Signature

interface SocketAddress extends declare<NetAddress_.SocketAddress> {
constructor(_: never);
readonly Rebuild: SocketAddress;
}

String

interface
Since v4.0.0

Type-level representation of String.

Signature

interface String extends Bottom<string, string, never, never, SchemaAST.String, String> {
constructor(_: never);
}

Type-level representation of StringForLiteralAutocomplete.

Signature

interface StringForLiteralAutocomplete extends Bottom<string & {}, string & {}, never, never, SchemaAST.String, StringForLiteralAutocomplete> {
constructor(_: never);
}
Since v3.10.0

Type-level representation of StringFromBase64.

Signature

interface StringFromBase64 extends decodeTo<String, String> {
constructor(_: never);
readonly Rebuild: StringFromBase64;
}
Since v3.10.0

Type-level representation of StringFromBase64Url.

Signature

interface StringFromBase64Url extends decodeTo<String, String> {
constructor(_: never);
readonly Rebuild: StringFromBase64Url;
}

StringFromHex

interface
Since v3.10.0

Type-level representation of StringFromHex.

Signature

interface StringFromHex extends decodeTo<String, String> {
constructor(_: never);
readonly Rebuild: StringFromHex;
}
Since v3.12.0

Type-level representation of StringFromUriComponent.

Signature

interface StringFromUriComponent extends decodeTo<String, String> {
constructor(_: never);
readonly Rebuild: StringFromUriComponent;
}
Since v4.0.0

A Tree of string | undefined nodes. Leaf values are either a string representation or undefined for opaque/declaration types.

Signature

type StringTree = Tree<string | undefined>

Struct

interface
Since v3.10.0

Type-level representation returned by Struct.

Signature

interface Struct<Fields extends Struct.Fields> extends BottomLazy<SchemaAST.Objects, Struct<Fields>> {
constructor(_: never);
readonly "~type.make": MakeInView<Fields>;
readonly "~type.make.in": MakeInView<Fields>;
readonly DecodingServices: DecodingServices<Fields>;
readonly Encoded: View<Fields>;
readonly EncodingServices: EncodingServices<Fields>;
readonly fields: Fields;
readonly Iso: View<Fields>;
readonly Type: View<Fields>;
mapFields<To extends Fields>(f: (fields: Fields) => To, options?: {
readonly unsafePreserveChecks?: boolean;
}): Struct<{ [K in string | number | symbol]: Readonly<To>[K] }>;
}
Since v4.0.0

Type-level representation returned by StructWithRest.

Signature

interface StructWithRest<S extends StructWithRest.Objects, Records extends StructWithRest.Records> extends BottomLazy<SchemaAST.Objects, StructWithRest<S, Records>> {
constructor(_: never);
readonly "~type.make": { [K in string | number | symbol]: MakeIn<S, Records>[K] };
readonly "~type.make.in": { [K in string | number | symbol]: MakeIn<S, Records>[K] };
readonly DecodingServices: DecodingServices<S, Records>;
readonly Encoded: { [K in string | number | symbol]: Encoded<S, Records>[K] };
readonly EncodingServices: EncodingServices<S, Records>;
readonly Iso: { [K in string | number | symbol]: Iso<S, Records>[K] };
readonly records: Records;
readonly schema: S;
readonly Type: { [K in string | number | symbol]: Type<S, Records>[K] };
}

suspend

interface
Since v3.10.0

Type-level representation returned by suspend.

Signature

interface suspend<S extends Constraint> extends BottomLazy<SchemaAST.Suspend, suspend<S>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly Type: S["Type"];
}

Symbol

interface
Since v4.0.0

Type-level representation of Symbol.

Signature

interface Symbol extends Bottom<symbol, symbol, never, never, SchemaAST.Symbol, Symbol> {
constructor(_: never);
}
Since v3.10.0

Type-level representation returned by TaggedStruct.

Signature

type TaggedStruct<Tag extends SchemaAST.LiteralValue, Fields extends Struct.Fields> = Struct<Simplify<{
readonly _tag: tag<Tag>;
} & Fields>>

TaggedUnion

interface
Since v4.0.0

Type-level representation returned by TaggedUnion.

Signature

interface TaggedUnion<Cases extends Record<string, Constraint>> extends BottomLazy<SchemaAST.Union<SchemaAST.Objects>, TaggedUnion<Cases>> {
constructor(_: never);
readonly "~type.make": { [K in string | number | symbol]: Cases[K]["~type.make"] }[keyof Cases];
readonly "~type.make.in": { [K in string | number | symbol]: Cases[K]["~type.make"] }[keyof Cases];
readonly cases: Cases;
readonly DecodingServices: { [K in string | number | symbol]: Cases[K]["DecodingServices"] }[keyof Cases];
readonly Encoded: { [K in string | number | symbol]: Cases[K]["Encoded"] }[keyof Cases];
readonly EncodingServices: { [K in string | number | symbol]: Cases[K]["EncodingServices"] }[keyof Cases];
readonly guards: { [K in string | number | symbol]: (u: unknown) => u is Cases[K]["Type"] };
readonly isAnyOf: <Keys>(keys: readonly Array<Keys>) => (value: Cases[keyof Cases]["Type"]) => value is Extract<Cases[keyof Cases]["Type"], {
_tag: Keys;
}>;
readonly Iso: { [K in string | number | symbol]: Cases[K]["Type"] }[keyof Cases];
readonly match: {
<Output>(cases: { [K in string | number | symbol]: (value: Cases[K]["Type"]) => Output }): (value: Cases[keyof Cases]["Type"]) => Output;
<Output>(value: Cases[keyof Cases]["Type"], cases: { [K in string | number | symbol]: (value: Cases[K]["Type"]) => Output }): Output;
};
readonly matchOrElse: {
<Output>(value: Cases[keyof Cases]["Type"], cases: { [K in string | number | symbol]: (value: Cases[K]["Type"]) => Output }, orElse: (value: Cases[keyof Cases]["Type"]) => Output): Output;
<Output>(cases: { [K in string | number | symbol]: (value: Cases[K]["Type"]) => Output }, orElse: (value: Cases[keyof Cases]["Type"]) => Output): (value: Cases[keyof Cases]["Type"]) => Output;
};
readonly tag: "_tag";
readonly Type: { [K in string | number | symbol]: Cases[K]["Type"] }[keyof Cases];
}
Since v3.10.0

Type-level representation returned by TemplateLiteral.

Signature

interface TemplateLiteral<Parts extends TemplateLiteral.Parts> extends Bottom<TemplateLiteral.Encoded<Parts>, TemplateLiteral.Encoded<Parts>, never, never, SchemaAST.TemplateLiteral, TemplateLiteral<Parts>> {
constructor(_: never);
readonly parts: Parts;
}
Since v3.10.0

Type-level representation returned by TemplateLiteralParser.

Signature

interface TemplateLiteralParser<Parts extends TemplateLiteral.Parts> extends BottomLazy<SchemaAST.Arrays, TemplateLiteralParser<Parts>> {
constructor(_: never);
readonly "~type.make": Type<Parts>;
readonly "~type.make.in": Type<Parts>;
readonly DecodingServices: Extract<Parts[number], Constraint>["DecodingServices"];
readonly Encoded: Encoded<Parts>;
readonly EncodingServices: Extract<Parts[number], Constraint>["EncodingServices"];
readonly Iso: Type<Parts>;
readonly parts: Parts;
readonly Type: Type<Parts>;
}

TimeZone

interface
Since v3.10.0

Type-level representation of TimeZone.

Signature

interface TimeZone extends declare<DateTime.TimeZone> {
constructor(_: never);
readonly Rebuild: TimeZone;
}
Since v4.0.0

Type-level representation of TimeZoneFromString.

Signature

interface TimeZoneFromString extends decodeTo<TimeZone, String> {
constructor(_: never);
readonly Rebuild: TimeZoneFromString;
}

TimeZoneNamed

interface
Since v3.10.0

Type-level representation of TimeZoneNamed.

Signature

interface TimeZoneNamed extends declare<DateTime.TimeZone.Named> {
constructor(_: never);
readonly Rebuild: TimeZoneNamed;
}
Since v4.0.0

Type-level representation of TimeZoneNamedFromString.

Signature

interface TimeZoneNamedFromString extends decodeTo<TimeZoneNamed, String> {
constructor(_: never);
readonly Rebuild: TimeZoneNamedFromString;
}
Since v3.10.0

Type-level representation of TimeZoneOffset.

Signature

interface TimeZoneOffset extends declare<DateTime.TimeZone.Offset> {
constructor(_: never);
readonly Rebuild: TimeZoneOffset;
}

Top

interface
Since v4.0.0

The existential "any schema" type โ€” all type parameters are erased to unknown.

Details

Use Top as a constraint when writing generic utilities that must accept any schema regardless of its Type, Encoded, or service requirements. It is the widest possible schema type and therefore gives you the least static information.

In user code prefer the narrower interfaces:

  • Schema<T> โ€” when you only care about the decoded type
  • Codec<T, E, RD, RE> โ€” when you need the encoded type and service requirements
  • ConstraintDecoder<T, RD> โ€” for decode-only APIs
  • ConstraintEncoder<E, RE> โ€” for encode-only APIs

Signature

interface Top extends Bottom<unknown, unknown, unknown, unknown, SchemaAST.AST, Top, unknown, unknown, any, unknown, Mutability, Optionality, ConstructorDefault, Mutability, Optionality> {
constructor(_: never);
}

Tree

type
Since v4.0.0

Recursive tree type whose leaves are Node values and whose branches are readonly arrays or string-keyed records of child trees.

Signature

type Tree<Node> = Node | TreeRecord<Node> | ReadonlyArray<Tree<Node>>

TreeRecord

interface
Since v4.0.0

A record node in a Tree: an object mapping string keys to child Tree nodes.

Signature

interface TreeRecord<A> {
[x: string]: Tree<A>;
}

Trim

interface
Since v3.10.0

Type-level representation of Trim.

Signature

interface Trim extends decodeTo<Trimmed, String> {
constructor(_: never);
readonly Rebuild: Trim;
}

Trimmed

interface
Since v3.10.0

Type-level representation of Trimmed.

Signature

interface Trimmed extends String {
constructor(_: never);
readonly Rebuild: Trimmed;
}

Tuple

interface
Since v3.10.0

Type-level representation returned by Tuple.

Signature

interface Tuple<Elements extends Tuple.Elements> extends BottomLazy<SchemaAST.Arrays, Tuple<Elements>> {
constructor(_: never);
readonly "~type.make": MakeIn_<Elements>;
readonly "~type.make.in": MakeIn_<Elements>;
readonly DecodingServices: DecodingServices<Elements>;
readonly elements: Elements;
readonly Encoded: Encoded_<Elements>;
readonly EncodingServices: EncodingServices<Elements>;
readonly Iso: Iso_<Elements>;
readonly Type: Type_<Elements>;
mapElements<To extends Elements>(f: (elements: Elements) => To, options?: {
readonly unsafePreserveChecks?: boolean;
}): Tuple<{ [K in string | number | symbol]: Readonly<To>[K] }>;
}

TupleWithRest

interface
Since v4.0.0

Type-level representation returned by TupleWithRest.

Signature

interface TupleWithRest<S extends TupleWithRest.TupleType, Rest extends TupleWithRest.Rest> extends BottomLazy<SchemaAST.Arrays, TupleWithRest<S, Rest>> {
constructor(_: never);
readonly "~type.make": MakeIn<S["~type.make"], Rest>;
readonly "~type.make.in": MakeIn<S["~type.make"], Rest>;
readonly DecodingServices: S["DecodingServices"] | Rest[number]["DecodingServices"];
readonly Encoded: Encoded<S["Encoded"], Rest>;
readonly EncodingServices: S["EncodingServices"] | Rest[number]["EncodingServices"];
readonly Iso: Iso<S["Iso"], Rest>;
readonly rest: Rest;
readonly schema: S;
readonly Type: Type<S["Type"], Rest>;
}

Uint8Array

interface
Since v4.0.0

Type-level representation of Uint8Array.

Signature

interface Uint8Array extends instanceOf<globalThis.Uint8Array<ArrayBufferLike>> {
constructor(_: never);
readonly Rebuild: Uint8Array;
}
Since v3.10.0

Type-level representation of Uint8ArrayFromBase64.

Signature

interface Uint8ArrayFromBase64 extends decodeTo<Uint8Array, String> {
constructor(_: never);
readonly Rebuild: Uint8ArrayFromBase64;
}
Since v3.10.0

Type-level representation of Uint8ArrayFromBase64Url.

Signature

interface Uint8ArrayFromBase64Url extends decodeTo<Uint8Array, String> {
constructor(_: never);
readonly Rebuild: Uint8ArrayFromBase64Url;
}
Since v3.10.0

Type-level representation of Uint8ArrayFromHex.

Signature

interface Uint8ArrayFromHex extends decodeTo<Uint8Array, String> {
constructor(_: never);
readonly Rebuild: Uint8ArrayFromHex;
}

Undefined

interface
Since v3.10.0

Type-level representation of Undefined.

Signature

interface Undefined extends Bottom<undefined, undefined, never, never, SchemaAST.Undefined, Undefined> {
constructor(_: never);
}

UndefinedOr

interface
Since v3.10.0

Type-level representation returned by UndefinedOr.

Signature

interface UndefinedOr<S extends Constraint> extends Union<readonly [S, Undefined]> {
constructor(_: never);
readonly Rebuild: UndefinedOr<S>;
}

Union

interface
Since v3.10.0

Type-level representation returned by Union.

Signature

interface Union<Members extends ReadonlyArray<Constraint>> extends BottomLazy<SchemaAST.Union<{ [K in keyof Members]: Members[K]["ast"] }[number]>, Union<Members>> {
constructor(_: never);
readonly "~type.make": { [K in string | number | symbol]: Members[K]["~type.make"] }[number];
readonly "~type.make.in": { [K in string | number | symbol]: Members[K]["~type.make"] }[number];
readonly DecodingServices: { [K in string | number | symbol]: Members[K]["DecodingServices"] }[number];
readonly Encoded: { [K in string | number | symbol]: Members[K]["Encoded"] }[number];
readonly EncodingServices: { [K in string | number | symbol]: Members[K]["EncodingServices"] }[number];
readonly Iso: { [K in string | number | symbol]: Members[K]["Iso"] }[number];
readonly members: Members;
readonly Type: { [K in string | number | symbol]: Members[K]["Type"] }[number];
mapMembers<To extends readonly Array<Constraint>>(f: (members: Members) => To, options?: {
readonly unsafePreserveChecks?: boolean;
}): Union<{ [K in string | number | symbol]: Readonly<To>[K] }>;
}

UniqueArray

interface
Since v4.0.0

Type-level representation returned by UniqueArray.

Signature

interface UniqueArray<S extends Constraint> extends $Array<S> {
constructor(_: never);
readonly Rebuild: UniqueArray<S>;
}

UniqueSymbol

interface
Since v4.0.0

Type-level representation returned by UniqueSymbol.

Signature

interface UniqueSymbol<sym extends symbol> extends Bottom<sym, sym, never, never, SchemaAST.UniqueSymbol, UniqueSymbol<sym>> {
constructor(_: never);
}

UnixPathAddress

interface unstable
Since v4.0.0

Type-level representation of UnixPathAddress.

Signature

interface UnixPathAddress extends declare<NetAddress_.UnixPathAddress> {
constructor(_: never);
readonly Rebuild: UnixPathAddress;
}

UnixPathAddressFromString

interface unstable
Since v4.0.0

Type-level representation of UnixPathAddressFromString.

Signature

interface UnixPathAddressFromString extends decodeTo<UnixPathAddress, String> {
constructor(_: never);
readonly Rebuild: UnixPathAddressFromString;
}

Unknown

interface
Since v3.10.0

Type-level representation of Unknown.

Signature

interface Unknown extends Bottom<unknown, unknown, never, never, SchemaAST.Unknown, Unknown> {
constructor(_: never);
}

URL

interface
Since v4.0.0

Type-level representation of URL.

Signature

interface URL extends instanceOf<globalThis.URL> {
constructor(_: never);
readonly Rebuild: URL;
}

URLFromString

interface
Since v4.0.0

Type-level representation of URLFromString.

Signature

interface URLFromString extends decodeTo<URL, String> {
constructor(_: never);
readonly Rebuild: URLFromString;
}

UrlParams

interface unstable
Since v4.0.0

Type-level representation of UrlParams.

Signature

interface UrlParams extends declare<UrlParams_.UrlParams, ReadonlyArray<readonly [string, string]>> {
constructor(_: never);
readonly Rebuild: UrlParams;
}
Since v4.0.0

Type-level representation of URLSearchParams.

Signature

interface URLSearchParams extends instanceOf<globalThis.URLSearchParams> {
constructor(_: never);
readonly Rebuild: URLSearchParams;
}

Void

interface
Since v3.10.0

Type-level representation of Void.

Signature

interface Void extends Bottom<void, void, never, never, SchemaAST.Void, Void> {
constructor(_: never);
}

Constraint used to ensure a schema field does not already have a constructor default.

Details

Only schemas that satisfy this constraint can be passed to withConstructorDefault.

Signature

interface WithoutConstructorDefault {
readonly "~type.constructor.default": "no-default";
}

Options

Details

  • encodingStrategy:
    • "passthrough" (default): pass the value through during encoding
    • "omit": omit the key from the encoded output

Signature

type DecodingDefaultOptions = {
readonly encodingStrategy?: "omit" | "passthrough";
}

ErrorOptions

interface
Since v4.0.0

Options for ErrorInstance and Defect.

Signature

interface ErrorOptions {
readonly excludeCause?: boolean;
readonly includeStack?: boolean;
}

MakeOptions

interface
Since v3.13.4

Options for makeEffect, make, and Class constructors.

When to use

Use when passing disableChecks: true to skip validation when you trust the data. Pass parseOptions to control parsing behavior.

See

Signature

interface MakeOptions {
readonly disableChecks?: boolean;
readonly parseOptions?: ParseOptions;
}
Since v4.0.0

Options for reference allocation and JSON Schema generation in toJsonSchemaDocument.

Details

The inherited referencePolicy runs after the input schema is converted to its canonical JSON codec, so it receives canonical JSON-encoded ASTs. The remaining options control compilation of the resulting live representation.

Gotchas

When these options are passed directly to SchemaRepresentation.toJsonSchemaDocument or SchemaRepresentation.toJsonSchemaMultiDocument, reference allocation has already happened and referencePolicy has no effect.

Signature

interface ToJsonSchemaOptions extends ToRepresentationOptions {
readonly generateDescriptions?: boolean;
readonly includeAnnotationKey?: (key: string) => boolean;
readonly onExcessProperty?: "error" | "ignore";
}

Other

Since v4.0.0

Namespace of type-level helpers for Codec.

Since v3.10.0

Namespace for Record type utilities.

Details

  • Record.Key โ€” constraint for the key schema (must encode to PropertyKey)
  • Record.Type<K, V> โ€” decoded type of the record
  • Record.Encoded<K, V> โ€” encoded type of the record
Since v3.10.0

Namespace of type-level helpers for Schema.

Since v3.10.0

Namespace for struct field type utilities.

Details

These types compute the decoded Type, encoded Encoded, and constructor input MakeIn of a Struct from its field map, handling optional, mutable, and other field modifiers automatically.

  • Struct.Fields โ€” constraint for the field map object
  • Struct.Type<F> โ€” decoded type of the struct
  • Struct.Encoded<F> โ€” encoded type of the struct
  • Struct.MakeIn<F> โ€” constructor input (optional/defaulted fields may be omitted)
  • Struct.DecodingServices<F> / Struct.EncodingServices<F> โ€” required services

Namespace for StructWithRest type utilities.

Details

  • StructWithRest.Type<S, R> โ€” decoded type (struct type intersected with record types)
  • StructWithRest.Encoded<S, R> โ€” encoded type

Namespace for TemplateLiteral helper types.

Namespace for TemplateLiteralParser helper types.

Since v3.10.0

Namespace for Tuple type utilities.

Details

  • Tuple.Elements โ€” constraint for the element schema array
  • Tuple.Type<E> โ€” decoded tuple type
  • Tuple.Encoded<E> โ€” encoded tuple type
  • Tuple.MakeIn<E> โ€” constructor input tuple

Namespace for TupleWithRest type utilities.

Details

  • TupleWithRest.TupleType โ€” constraint for the leading tuple schema
  • TupleWithRest.Rest โ€” the rest element schema(s)
  • TupleWithRest.Type<T, R> โ€” decoded type (fixed elements + rest)
  • TupleWithRest.Encoded<T, R> โ€” encoded type

Schemas

Since v3.10.0

Schema for the any type. Accepts any value without validation.

See

  • Unknown for a safer alternative that uses unknown.

Signature

declare const Any: Any

Schema for BigDecimal values.

When to use

Use when you already have Effect decimal instances and need schema validation, formatting, equivalence, and JSON string serialization.

Details

Default JSON serializer:

  • encodes BigDecimal as a string

See

Signature

declare const BigDecimal: BigDecimal

Schema that parses a string into a BigDecimal.

When to use

Use to parse decimal or exponent-notation strings into arbitrary-precision BigDecimal values while encoding them back to strings.

Details

Decoding:

  • A string is decoded with BigDecimal.fromString.

Encoding:

  • A BigDecimal is encoded with BigDecimal.format.

Gotchas

An empty string decodes as zero.

See

Signature

declare const BigDecimalFromString: BigDecimalFromString
Since v4.0.0

Schema for bigint values. Validates that the input is typeof "bigint".

When to use

Use when the input is already a bigint and the schema should validate and preserve bigint values without parsing from another representation.

See

Signature

declare const BigInt: BigInt

Schema that parses a string into a bigint.

When to use

Use to parse signed base-10 integer strings into bigint values while encoding bigint values back to decimal strings.

Details

Decoding:

  • A string is decoded as a bigint.

Encoding:

  • A bigint is encoded as a string.

Gotchas

Decoding accepts only strings matching ^-?\d+$.

See

Signature

declare const BigIntFromString: BigIntFromString
Since v4.0.0

Schema for boolean values. Validates that the input is typeof "boolean".

When to use

Use to validate values that are already JavaScript booleans.

See

  • BooleanFromBit for a schema that decodes bit literals 0 or 1 into a boolean

Signature

declare const Boolean: Boolean

Schema for a boolean parsed from 0 or 1.

When to use

Use when decoding data sources that represent booleans as 0 | 1 while keeping boolean values in the decoded model.

Details

Decoding accepts only 0 | 1, maps 1 to true, and maps 0 to false. Encoding maps true to 1 and false to 0.

See

  • Boolean for validating values that are already booleans
  • Literals for keeping bit literals instead of decoding them

Signature

declare const BooleanFromBit: BooleanFromBit

ByteSize

unstable
Since v4.0.0

Schema for exact, non-negative ByteSize values.

Details

The JSON codec encodes the byte count as a bigint string, preserving values beyond JavaScript's safe-integer range. The StringTree codec uses the human-readable byte-size syntax exposed by ByteSizeFromString.

Signature

declare const ByteSize: ByteSize
Since v4.0.0

Schema that decodes non-negative bigint byte counts.

Signature

declare const ByteSizeFromBigInt: ByteSizeFromBigInt
Since v4.0.0

Schema that decodes non-negative safe-integer byte counts.

Details

Encoding fails when the byte count exceeds Number.MAX_SAFE_INTEGER.

Signature

declare const ByteSizeFromNumber: ByteSizeFromNumber
Since v4.0.0

Schema that decodes byte-size strings into exact, non-negative ByteSize values.

Details

Decoding accepts an unsigned base-10 integer or decimal followed by optional whitespace and one of these case-sensitive units:

  • bytes: B, byte, or bytes
  • decimal SI units (powers of 1,000): kB, MB, GB, TB, PB, EB, ZB, YB, RB, or QB, plus their lowercase singular and plural names
  • binary IEC units (powers of 1,024): KiB, MiB, GiB, TiB, PiB, EiB, ZiB, or YiB, plus their lowercase singular and plural names

Leading and trailing whitespace is ignored. A decimal quantity must resolve to an integral number of bytes, so 1.5 kB is accepted while 0.1 KiB is rejected.

Encoding returns the exact byte count as <count> byte or <count> bytes.

Gotchas

A unit is required. Signs, exponent notation, digit separators, and ambiguous unit spellings such as KB, mb, Mb, or b are rejected.

Signature

declare const ByteSizeFromString: ByteSizeFromString
Since v3.10.0

Creates a schema for Cause values using separate schemas for typed failures and unexpected defects.

When to use

Use to validate, transform, or serialize Effect failure causes when typed failures and unexpected defects need separate schemas.

Details

The error schema is applied to Fail reasons and the defect schema is applied to Die reasons. Interrupt reasons do not use either schema and carry only an optional fiber id.

See

  • CauseReason for the schema used by each individual cause reason
  • CauseIso for the ordered array representation used by the schema ISO

Signature

declare function Cause<E extends Constraint, D extends Constraint>(error: E, defect: D): Cause<E, D>

Creates a schema for Cause.Reason values using separate schemas for typed failures and unexpected defects.

When to use

Use when serializing or decoding individual cause reasons separately from a full failure cause, with distinct schemas for typed errors and defects.

Details

Fail reasons use the error schema, Die reasons use the defect schema, and Interrupt reasons carry only an optional fiber id.

See

  • Cause for constructing schemas for full Cause values
  • CauseReasonIso for the ISO shape of each cause reason

Signature

declare function CauseReason<E extends Constraint, D extends Constraint>(error: E, defect: D): CauseReason<E, D>
Since v3.10.0

Schema for strings whose JavaScript length is exactly 1.

When to use

Use to validate string values that must have length === 1.

Gotchas

This schema uses JavaScript String.length, so visible characters made from multiple UTF-16 code units do not satisfy length === 1.

See

Signature

declare const Char: Char
Since v3.10.0

Schema for chunks whose values conform to the provided element schema.

Signature

declare function Chunk<Value extends Constraint>(value: Value): Chunk<Value>

Cookies

unstable
Since v4.0.0

Schema for HTTP cookie collections.

Details

JSON encoding uses Set-Cookie header strings, while isomorphic encoding uses a readonly record of cookie values.

Signature

declare const Cookies: Cookies
Since v4.0.0

Schema for valid JavaScript Date objects.

When to use

Use to validate in-memory values that must already be valid JavaScript date objects.

Details

This schema accepts Date instances whose timestamp is not NaN. The default JSON serializer encodes dates as ISO 8601 strings.

See

Signature

declare const Date: Date

Example Defining a Date schema

import { Schema } from "effect"
const date = Schema.decodeUnknownSync(Schema.Date)(new Date("2024-01-01"))
date.toISOString() // => "2024-01-01T00:00:00.000Z"

Schema that decodes epoch milliseconds into a JavaScript Date.

When to use

Use to model numeric millisecond timestamps that decode to JavaScript Date objects and encode back to numbers.

Details

Decoding: A safe integer number of milliseconds since the Unix epoch is decoded as a Date.

Encoding: A Date is encoded as its millisecond timestamp.

Gotchas

JavaScript Date supports a narrower range than safe integers, so integers outside the supported Date range fail decoding.

See

Signature

declare const DateFromMillis: DateFromMillis

Schema that decodes a string into a JavaScript Date.

When to use

Use to model string-encoded dates that decode to JavaScript Date objects and encode back to strings.

Details

Decoding: The string is passed to JavaScript Date construction.

Encoding: A Date is encoded as an ISO string.

Invalid date strings fail decoding.

See

Signature

declare const DateFromString: DateFromString

Schema for DateTime.Utc values.

When to use

Use to validate existing DateTime.Utc schema values and use the default JSON codec that represents them as UTC ISO strings.

Details

The default JSON codec decodes UTC ISO strings into DateTime.Utc values and encodes DateTime.Utc values as UTC ISO strings.

See

Signature

declare const DateTimeUtc: DateTimeUtc

Schema that decodes a Date into a DateTime.Utc.

When to use

Use when you need to decode valid JavaScript Date objects into DateTime.Utc values.

Details

Decoding:

  • A valid Date is decoded as a DateTime.Utc

Encoding:

  • A DateTime.Utc is encoded as a Date

See

Signature

declare const DateTimeUtcFromDate: DateTimeUtcFromDate

Schema that decodes a number into a DateTime.Utc.

Details

Decoding:

  • A number of milliseconds since the Unix epoch is decoded as a DateTime.Utc

Encoding:

  • A DateTime.Utc is encoded as a number of milliseconds since the Unix epoch.

See

Signature

declare const DateTimeUtcFromMillis: DateTimeUtcFromMillis

Schema that decodes a date-time string into a DateTime.Utc.

Details

Decoding:

  • A string accepted by DateTime.make is parsed and normalized to UTC. Strings without an explicit zone are interpreted as UTC.

Encoding:

  • A DateTime.Utc is encoded as a UTC ISO 8601 string.

See

Signature

declare const DateTimeUtcFromString: DateTimeUtcFromString

Schema for DateTime.Zoned values.

Details

Default JSON serializer:

  • encodes offset zones as an ISO date-time with a numeric offset, such as YYYY-MM-DDTHH:mm:ss.sss+HH:MM
  • encodes named zones by appending the IANA identifier in brackets, such as YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]

Signature

declare const DateTimeZoned: DateTimeZoned

Schema that parses a zoned DateTime string into a DateTime.Zoned.

Details

Decoding:

  • A string (e.g. 2024-01-01T00:00:00.000+00:00[Europe/London]) is decoded as a DateTime.Zoned.

Encoding:

  • A DateTime.Zoned is encoded as a string.

Signature

declare const DateTimeZonedFromString: DateTimeZonedFromString
Since v4.0.0

Schema for unexpected defect values represented as unknown with a JSON encoded form.

When to use

Use when you need a schema for Cause defects or other unexpected failures whose runtime value may be any value.

Details

The encoded side is Json. During decoding, JSON objects with a string message property are decoded into JavaScript Error values, preserving a non-default name and any string stack. Other JSON values decode unchanged.

During encoding, JavaScript Error values encode to JSON objects with name, message, and optional cause properties. Pass { includeStack: true } to include string stack traces in encoded Error defects, or { excludeCause: true } to omit causes. Other values are serialized through Effect's JSON formatter and then parsed back into JSON when possible.

Gotchas

This schema is for carrying defects across JSON boundaries, not for preserving every JavaScript value exactly. Some values cannot round-trip unchanged:

  • A non-Error object such as { message: "boom" } encodes as an error-shaped JSON object and decodes back as an Error.
  • JSON serialization normalizes unsupported values. For example, undefined array elements encode as null, unsupported object properties are omitted, and circular references are dropped.
  • Values that cannot be represented as JSON fall back to Effect's formatted string representation.

See

  • ErrorInstance for a schema that only accepts JavaScript Error values.

Signature

declare function Defect(options?: ErrorOptions): Defect

Schema for already-constructed IPv6 address (AAAA) DNS records.

Signature

declare const DnsAaaaRecord: DnsAaaaRecord

Schema for already-constructed IPv4 address (A) DNS records.

Signature

declare const DnsARecord: DnsARecord

Schema for already-constructed certification authority authorization (CAA) DNS records.

Signature

declare const DnsCaaRecord: DnsCaaRecord

Schema for already-constructed canonical name (CNAME) DNS records.

Signature

declare const DnsCnameRecord: DnsCnameRecord

Schema for already-constructed mail exchange (MX) DNS records.

Signature

declare const DnsMxRecord: DnsMxRecord

Schema for already-constructed naming authority pointer (NAPTR) DNS records.

Signature

declare const DnsNaptrRecord: DnsNaptrRecord

Schema for already-constructed name server (NS) DNS records.

Signature

declare const DnsNsRecord: DnsNsRecord

Schema for already-constructed pointer (PTR) DNS records.

Signature

declare const DnsPtrRecord: DnsPtrRecord

Schema for already-constructed DNS records of any supported record type.

Details

The default JSON serializer encodes records as objects tagged by record type, with addresses and names as canonical strings, SOA timers as whole seconds, and TLSA data as hex, such as { "_tag": "SRV", "target": "db.internal", "port": 5432, "priority": 10, "weight": 5 }. Decoding accepts only canonical addresses and normalized domain names, and reports invalid fields with their path.

Signature

declare const DnsRecord: DnsRecord

Schema for supported DNS record types such as "A" or "SRV".

Signature

declare const DnsRecordType: DnsRecordType

Schema for already-constructed start of authority (SOA) DNS records.

Signature

declare const DnsSoaRecord: DnsSoaRecord

Schema for already-constructed service locator (SRV) DNS records.

Signature

declare const DnsSrvRecord: DnsSrvRecord

Schema for already-constructed TLS authentication (TLSA) DNS records.

Details

The default JSON serializer encodes the certificate association data as a hex string.

Signature

declare const DnsTlsaRecord: DnsTlsaRecord

Schema for already-constructed text (TXT) DNS records.

Signature

declare const DnsTxtRecord: DnsTxtRecord

Schema for normalized DNS domain names.

Details

Only names already in normalized form (lowercase ASCII, with internationalized labels in xn-- form) are accepted. Use DomainNameFromString to normalize arbitrary input.

Signature

declare const DomainName: DomainName

Schema for DNS domain names decoded from strings, normalizing case and converting internationalized names to their ASCII form.

Signature

declare const DomainNameFromString: DomainNameFromString
Since v3.10.0

Schema for Duration values.

Details

The default JSON serializer encodes Duration as a tagged object with the duration type and value.

Signature

declare const Duration: Duration

Example Defining a Duration schema

import { Duration, Schema } from "effect"
Schema.decodeUnknownSync(Schema.Duration)(Duration.seconds(5)) // => Duration.seconds(5)

Schema that decodes a number into a Duration, treating the number as milliseconds.

Details

Decoding:

  • A finite or infinite number is decoded as a Duration

Encoding:

  • A Duration is encoded to a finite or infinite number of milliseconds

Gotchas

NaN is decoded as Duration.zero, matching Duration.millis.

Signature

declare const DurationFromMillis: DurationFromMillis

Schema that decodes a bigint into a Duration, treating the bigint as nanoseconds.

Details

Decoding: A bigint representing nanoseconds is decoded as a Duration.

Encoding: Finite durations are encoded as a bigint number of nanoseconds. Encoding fails when the duration cannot be represented as nanoseconds, such as Duration.infinity or Duration.negativeInfinity.

Signature

declare const DurationFromNanos: DurationFromNanos

Schema that parses a string into a Duration.

Details

Decoding:

  • A string is decoded as a Duration, accepting any format that Duration.fromInput can parse.

Encoding:

  • A Duration is encoded as a parseable string.

Signature

declare const DurationFromString: DurationFromString

Schema for JavaScript Error objects.

Details

Default JSON serializer:

Encodes an Error as an object with message, optional name, and optional cause properties, and decodes that object back into an Error. Stack traces are omitted by default for security. Pass { includeStack: true } to include stack traces, or { excludeCause: true } to omit causes.

Signature

declare function ErrorInstance(options?: ErrorOptions): ErrorInstance
Since v3.10.0

Creates a schema for Exit values using schemas for the success value, typed failure, and unexpected defect channels.

When to use

Use when serializing or validating an effect outcome where success, typed failure, and defects each need their own schema.

Signature

declare function Exit<A extends Constraint, E extends Constraint, D extends Constraint>(value: A, error: E, defect: D): Exit<A, E, D>
Since v4.0.0

Schema for JavaScript File objects.

Details

The default JSON serializer encodes a File as { data, type, name, lastModified } where data is base64-encoded.

Signature

declare const File: File
Since v3.10.0

Schema for finite numbers, rejecting NaN, Infinity, and -Infinity.

Signature

declare const Finite: Finite

Schema that parses a string into a finite number.

Details

Decoding:

  • A string is decoded as a finite number, rejecting NaN, Infinity, and -Infinity values.

Encoding:

  • A finite number is encoded as a string.

Signature

declare const FiniteFromString: FiniteFromString
Since v4.0.0

Schema for JavaScript FormData objects.

Details

The default JSON serializer encodes a FormData as an array of [key, entry] pairs where each entry is tagged as "String" or "File".

Signature

declare const FormData: FormData

Returns a schema that decodes a JSON string and then decodes the parsed value using the given schema.

Details

This is useful when working with JSON-encoded strings where the actual structure of the value is known and described by an existing schema.

During decoding, the resulting schema first parses the input string as JSON, using reviver when provided, and then runs the provided schema on the parsed result. During encoding, it first encodes with the provided schema and then passes the result to JSON.stringify with the optional replacer and space.

Signature

declare function fromJsonString<S extends Constraint>(schema: S, options?: {
readonly replacer?: JsonReplacer;
readonly reviver?: (this: any, key: string, value: any) => any;
readonly space?: string | number;
}): fromJsonString<S>

Example Formatting encoded JSON

import { Schema } from "effect"
const schema = Schema.Struct({ a: Schema.Number })
const schemaFromJsonString = Schema.fromJsonString(schema, { space: 2 })
Schema.encodeSync(schemaFromJsonString)({ a: 1 }) // => "{\n \"a\": 1\n}"

Graph

unstable
Since v4.0.0

Creates a schema for immutable directed or undirected Effect graphs.

Details

Encoding preserves active node and edge indexes, payloads, endpoints, isolated nodes, self-loops, parallel edges, and stored edge orientation. It does not encode removed-ID allocator history; after decoding, future allocation starts after the highest active decoded index. Encoding rejects mutable graphs. Graph.toJSON() remains an inspection summary and is not this wire format.

Signature

declare function Graph<Node extends Constraint, Edge extends Constraint>(type: "directed", node: Node, edge: Edge): Graph<"directed", Node, Edge>
declare function Graph<Node extends Constraint, Edge extends Constraint>(type: "undirected", node: Node, edge: Edge): Graph<"undirected", Node, Edge>
declare function Graph<T extends Kind, Node extends Constraint, Edge extends Constraint>(type: T, node: Node, edge: Edge): Graph<T, Node, Edge>

Example Encoding a directed graph as JSON

import { Graph, Schema } from "effect"
const codec = Schema.toCodecJson(Schema.Graph("directed", Schema.String, Schema.Number))
const graph = Graph.directed<string, number>((mutable) => {
const source = Graph.addNode(mutable, "A")
const target = Graph.addNode(mutable, "B")
Graph.addEdge(mutable, source, target, 1)
})
const encoded = Schema.encodeSync(codec)(graph)
encoded.type // => "directed"
encoded.nodes // => [{ index: 0, data: "A" }, { index: 1, data: "B" }]
encoded.edges // => [{ index: 0, source: 0, target: 1, data: 1 }]
Since v3.10.0

Schema for hash maps whose keys and values conform to the provided schemas.

Signature

declare function HashMap<Key extends Constraint, Value extends Constraint>(key: Key, value: Value): HashMap<Key, Value>
Since v3.10.0

Schema for hash sets whose values conform to the provided element schema.

Signature

declare function HashSet<Value extends Constraint>(value: Value): HashSet<Value>

Headers

unstable
Since v4.0.0

Schema for HTTP headers encoded as records of string values.

Details

Decoding normalizes header names; encoding returns a plain record.

Signature

declare const Headers: Headers
Since v4.0.0

Schema for hosts: numeric IP addresses, scoped IPv6 literals, or domain names.

Signature

declare const Host: Host

Schema for hosts decoded from strings. Numeric IP strings decode to IP addresses; other strings decode to scoped IPv6 literals or domain names.

Signature

declare const HostFromString: HostFromString
Since v4.0.0

Schema for already-constructed unresolved host and port values.

Signature

declare const HostPort: HostPort

Schema for unresolved endpoints encoded as host:port or [IPv6]:port strings.

Signature

declare const HostPortFromString: HostPortFromString

InetAddress

unstable
Since v4.0.0

Schema for already-constructed resolved internet addresses.

Signature

declare const InetAddress: InetAddress
Since v4.0.0

Schema for resolved internet addresses encoded as numeric socket strings.

Signature

declare const InetAddressFromString: InetAddressFromString
Since v4.0.0

Schema for already-constructed resolved IPv4 internet addresses.

Signature

declare const InetAddressV4: InetAddressV4
Since v4.0.0

Schema for already-constructed resolved IPv6 internet addresses.

Signature

declare const InetAddressV6: InetAddressV6
Since v3.10.0

Schema for integers, rejecting NaN, Infinity, and -Infinity.

Signature

declare const Int: Int

IpAddress

unstable
Since v4.0.0

Schema for already-constructed IPv4 or IPv6 address values.

Signature

declare const IpAddress: IpAddress
Since v4.0.0

Schema for IP addresses encoded as canonical numeric strings.

Signature

declare const IpAddressFromString: IpAddressFromString

IpInterface

unstable
Since v4.0.0

Schema for already-constructed IPv4 or IPv6 interface address values.

Signature

declare const IpInterface: IpInterface
Since v4.0.0

Schema for IPv4 or IPv6 interface addresses encoded as an address and prefix length.

Signature

declare const IpInterfaceFromString: IpInterfaceFromString
Since v4.0.0

Schema for already-constructed link-local IP addresses.

Signature

declare const IpLinkLocalAddress: IpLinkLocalAddress

Schema for link-local IP addresses encoded as numeric strings.

Signature

declare const IpLinkLocalAddressFromString: IpLinkLocalAddressFromString
Since v4.0.0

Schema for already-constructed loopback IP addresses.

Signature

declare const IpLoopbackAddress: IpLoopbackAddress

Schema for loopback IP addresses encoded as numeric strings.

Signature

declare const IpLoopbackAddressFromString: IpLoopbackAddressFromString
Since v4.0.0

Schema for already-constructed multicast IP addresses.

Signature

declare const IpMulticastAddress: IpMulticastAddress

Schema for multicast IP addresses encoded as numeric strings.

Signature

declare const IpMulticastAddressFromString: IpMulticastAddressFromString

Example Decoding a validated multicast address

import { assert } from "@effect/vitest"
import { Schema } from "effect"
import { NetAddress } from "effect/net"
const address = Schema.decodeUnknownSync(Schema.IpMulticastAddressFromString)("239.255.0.1")
assert.isTrue(NetAddress.isMulticast(address))

IpNetwork

unstable
Since v4.0.0

Schema for already-constructed canonical IPv4 or IPv6 network prefixes.

Signature

declare const IpNetwork: IpNetwork
Since v4.0.0

Schema for canonical IPv4 or IPv6 network prefixes encoded in CIDR notation.

Signature

declare const IpNetworkFromString: IpNetworkFromString
Since v4.0.0

Schema for already-constructed syntactic unicast IP addresses.

Signature

declare const IpUnicastAddress: IpUnicastAddress

Schema for syntactic unicast IP addresses encoded as numeric strings.

Signature

declare const IpUnicastAddressFromString: IpUnicastAddressFromString
Since v4.0.0

Schema for already-constructed unspecified IP addresses.

Signature

declare const IpUnspecifiedAddress: IpUnspecifiedAddress

Schema for unspecified IP addresses encoded as numeric strings.

Signature

declare const IpUnspecifiedAddressFromString: IpUnspecifiedAddressFromString

Ipv4Address

unstable
Since v4.0.0

Schema for already-constructed IPv4 address values.

Signature

declare const Ipv4Address: Ipv4Address
Since v4.0.0

Schema for IPv4 addresses encoded as canonical dotted-decimal strings.

Signature

declare const Ipv4AddressFromString: Ipv4AddressFromString
Since v4.0.0

Schema for the already-constructed IPv4 limited broadcast address.

Signature

declare const Ipv4BroadcastAddress: Ipv4BroadcastAddress

Schema for the IPv4 limited broadcast address encoded as a string.

Signature

declare const Ipv4BroadcastAddressFromString: Ipv4BroadcastAddressFromString
Since v4.0.0

Schema for already-constructed IPv4 interface address values.

Signature

declare const Ipv4Interface: Ipv4Interface

Schema for IPv4 interface addresses encoded as an address and prefix length.

Signature

declare const Ipv4InterfaceFromString: Ipv4InterfaceFromString

Ipv4Network

unstable
Since v4.0.0

Schema for already-constructed canonical IPv4 network prefixes.

Signature

declare const Ipv4Network: Ipv4Network
Since v4.0.0

Schema for canonical IPv4 network prefixes encoded in CIDR notation.

Signature

declare const Ipv4NetworkFromString: Ipv4NetworkFromString
Since v4.0.0

Schema for already-constructed RFC 1918 private-use addresses.

Signature

declare const Ipv4PrivateAddress: Ipv4PrivateAddress

Schema for RFC 1918 private-use addresses encoded as strings.

Signature

declare const Ipv4PrivateAddressFromString: Ipv4PrivateAddressFromString

Ipv6Address

unstable
Since v4.0.0

Schema for already-constructed IPv6 address values.

Signature

declare const Ipv6Address: Ipv6Address
Since v4.0.0

Schema for IPv6 addresses encoded as canonical strings.

Signature

declare const Ipv6AddressFromString: Ipv6AddressFromString
Since v4.0.0

Schema for already-constructed IPv6 interface address values.

Signature

declare const Ipv6Interface: Ipv6Interface

Schema for IPv6 interface addresses encoded as an address and prefix length.

Signature

declare const Ipv6InterfaceFromString: Ipv6InterfaceFromString

Ipv6Network

unstable
Since v4.0.0

Schema for already-constructed canonical IPv6 network prefixes.

Signature

declare const Ipv6Network: Ipv6Network
Since v4.0.0

Schema for canonical IPv6 network prefixes encoded in CIDR notation.

Signature

declare const Ipv6NetworkFromString: Ipv6NetworkFromString

Schema for already-constructed IPv6 unique-local addresses.

Signature

declare const Ipv6UniqueLocalAddress: Ipv6UniqueLocalAddress

Schema for IPv6 unique-local addresses encoded as strings.

Signature

declare const Ipv6UniqueLocalAddressFromString: Ipv6UniqueLocalAddressFromString
Since v4.0.0

Schema that accepts and validates any immutable JSON-compatible value.

Signature

declare const Json: Codec<Json, Json, never, never>

Example Validating a JSON value

import { Option, Schema } from "effect"
Schema.decodeUnknownOption(Schema.Json)({ key: [1, true, null] }) // => Option.some({ key: [1, true, null] })

Extracts a JSON value from the first occurrence of the given field in URL parameters.

Signature

declare const JsonFromUrlParamsField: (field: string, options?: {
readonly reviver?: (this: any, key: string, value: any) => any;
}) => JsonFromUrlParamsField

Example Decoding a JSON parameter field

import { Schema } from "effect"
import { UrlParams } from "effect/http"
const extractFoo = Schema.JsonFromUrlParamsField("foo").pipe(
Schema.decodeTo(Schema.Struct({
some: Schema.String,
number: Schema.Number
}))
)
const decoded = Schema.decodeSync(extractFoo)(UrlParams.fromInput({
foo: `{"some":"bar","number":42}`,
baz: "qux"
}))
const result = [decoded.some, decoded.number] // => ["bar", 42]

Schema for readonly string-keyed records whose values are JSON-compatible.

When to use

Use when you need to validate a JSON object rather than any JSON value.

See

  • Json for a schema that also accepts JSON arrays and primitive values

Signature

declare const JsonObject: $Record<String, Codec<Json, Json, never, never>>

Example Validating a JSON object

import { Option, Schema } from "effect"
Schema.decodeUnknownOption(Schema.JsonObject)({ key: [1, true, null] }) // => Option.some({ key: [1, true, null] })
Schema.decodeUnknownOption(Schema.JsonObject)([1, 2, 3]) // => Option.none()

MacAddress

unstable
Since v4.0.0

Schema for already-constructed MAC address values.

Signature

declare const MacAddress: MacAddress
Since v4.0.0

Schema for MAC addresses encoded as canonical colon-separated hexadecimal strings.

Signature

declare const MacAddressFromString: MacAddressFromString
Since v4.0.0

Schema for the already-constructed MAC all-ones broadcast address.

Signature

declare const MacBroadcastAddress: MacBroadcastAddress

Schema for the MAC all-ones broadcast address encoded as a string.

Signature

declare const MacBroadcastAddressFromString: MacBroadcastAddressFromString

Schema for already-constructed locally administered MAC addresses.

Signature

declare const MacLocallyAdministeredAddress: MacLocallyAdministeredAddress

Schema for locally administered MAC addresses encoded as strings.

Signature

declare const MacLocallyAdministeredAddressFromString: MacLocallyAdministeredAddressFromString
Since v4.0.0

Schema for already-constructed multicast MAC addresses.

Signature

declare const MacMulticastAddress: MacMulticastAddress

Schema for multicast MAC addresses encoded as canonical strings.

Signature

declare const MacMulticastAddressFromString: MacMulticastAddressFromString
Since v4.0.0

Schema for already-constructed unicast MAC addresses.

Signature

declare const MacUnicastAddress: MacUnicastAddress

Schema for unicast MAC addresses encoded as canonical strings.

Signature

declare const MacUnicastAddressFromString: MacUnicastAddressFromString

Schema for already-constructed universally administered MAC addresses.

Signature

declare const MacUniversallyAdministeredAddress: MacUniversallyAdministeredAddress

Schema for universally administered MAC addresses encoded as strings.

Signature

declare const MacUniversallyAdministeredAddressFromString: MacUniversallyAdministeredAddressFromString

Schema that accepts any mutable JSON-compatible value. See Json for the immutable variant.

Signature

declare const MutableJson: Codec<MutableJson, MutableJson, never, never>
Since v4.0.0

Schema for non-negative safe integers, including zero.

When to use

Use when you need a count, index, or size that cannot be negative.

See

  • Int for safe integers that may be negative

Signature

declare const Natural: Natural
Since v3.10.0

Schema for the never type. Always fails validation โ€” no value satisfies it.

Signature

declare const Never: Never

Schema for non-empty strings. Validates that a string has at least one character.

Signature

declare const NonEmptyString: NonEmptyString
Since v3.10.0

Schema for the null literal. Validates that the input is strictly null.

See

  • NullOr for a union with another schema.

Signature

declare const Null: Null
Since v4.0.0

Schema for number values, including NaN, Infinity, and -Infinity.

Details

Default JSON serializer:

  • Finite numbers are serialized as numbers.
  • Non-finite values are serialized as strings ("NaN", "Infinity", "-Infinity").

See

  • Finite for a schema that excludes non-finite values.

Signature

declare const Number: Number

Schema that parses a string into a number using JavaScript number coercion.

Details

Decoding: A string is decoded as a number, including possible non-finite values such as NaN, Infinity, and -Infinity. Use FiniteFromString to reject non-finite numbers.

Encoding: A number is encoded as a string.

Signature

declare const NumberFromString: NumberFromString

Schema for the object type. Validates that the input is a non-null object or function (i.e. typeof value === "object" && value !== null || typeof value === "function").

Signature

declare const ObjectKeyword: ObjectKeyword
Since v3.10.0

Schema for Option<A> values.

Signature

declare function Option<A extends Constraint>(value: A): Option<A>

Decodes a nullish value T to a required Option<T> value.

Details

Decoding maps null and undefined to None and all other values to Some. Encoding maps None to null or undefined depending on options.onNoneEncoding, which defaults to undefined, and maps Some to its value.

Signature

declare function OptionFromNullishOr<S extends Constraint>(schema: S, options?: {
onNoneEncoding: null | undefined;
}): OptionFromNullishOr<S>

Decodes a nullable, required value T to a required Option<T> value.

Details

Decoding maps null to None and all other values to Some. Encoding maps None to null and maps Some to its value.

Signature

declare function OptionFromNullOr<S extends Constraint>(schema: S): OptionFromNullOr<S>

Decodes an optional or undefined value A to a required Option<A> value.

Details

Decoding maps a missing key or a present undefined value to None, and maps all other values to Some. Encoding maps None to a missing key and maps Some to its value.

Signature

declare function OptionFromOptional<S extends Constraint>(schema: S): OptionFromOptional<S>

Decodes an optional value A to a required Option<A> value.

Details

Decoding maps a missing key to None and a present value to Some. Encoding maps None to a missing key and maps Some to its value.

Signature

declare function OptionFromOptionalKey<S extends Constraint>(schema: S): OptionFromOptionalKey<S>

Decodes an optional or null or undefined value A to a required Option<A> value.

Details

Decoding maps a missing key, undefined, or null to None, and maps all other values to Some. Encoding maps Some to its value. None is encoded according to options.onNoneEncoding: "omit" encodes a missing key, null encodes null, and undefined encodes undefined.

Signature

declare function OptionFromOptionalNullOr<S extends Constraint>(schema: S, options?: {
readonly onNoneEncoding: "omit" | null | undefined;
}): OptionFromOptionalNullOr<S>

Decodes a required value that may be undefined to a required Option<T> value.

Details

Decoding maps undefined to None and all other values to Some. Encoding maps None to undefined and maps Some to its value.

Signature

declare function OptionFromUndefinedOr<S extends Constraint>(schema: S): OptionFromUndefinedOr<S>
Since v4.0.0

Schema for TCP and UDP port numbers from 0 through 65535.

Details

Port 0 is accepted because it asks the operating system to choose a port when binding, and it matches the port range of InetAddress and HostPort. Config.Port accepts only 1 through 65535.

Signature

declare const Port: Port

Schema for property keys accepted by Effect schemas: finite number, symbol, or string.

Signature

declare const PropertyKey: Union<readonly [Finite, Symbol, String]>

Schema for readonly maps whose keys and values conform to the provided schemas.

Signature

declare function ReadonlyMap<Key extends Constraint, Value extends Constraint>(key: Key, value: Value): $ReadonlyMap<Key, Value>

Schema for readonly sets whose values conform to the provided element schema.

Signature

declare function ReadonlySet<Value extends Constraint>(value: Value): $ReadonlySet<Value>
Since v4.0.0

Schema that decodes HTTP cookies into a record of decoded string values keyed by cookie name.

Signature

declare const RecordFromCookies: RecordFromCookies
Since v4.0.0

Schema that decodes URL parameters into a record of string values.

Details

Keys with one value decode to a string, and keys with multiple values decode to a non-empty readonly array of strings.

Signature

declare const RecordFromUrlParams: RecordFromUrlParams

Example Decoding URL parameters to a record

import { Schema } from "effect"
import { UrlParams } from "effect/http"
const toStruct = Schema.RecordFromUrlParams.pipe(
Schema.decodeTo(Schema.Struct({
some: Schema.String,
number: Schema.FiniteFromString
}))
)
const decoded = Schema.decodeSync(toStruct)(UrlParams.fromInput({
some: "value",
number: 42
}))
const result = [decoded.some, decoded.number] // => ["value", 42]
Since v3.10.0

Schema for Redacted values, which hide their contents from inspection.

Details

Options:

  • label: When provided, the schema will behave as follows:
    • Values will be validated against the label in addition to the wrapped schema
    • The default JSON serializer will deserialize into a Redacted instance with the label
    • The arbitrary generator will produce a Redacted instance with the label
    • The formatter will return the label
  • disallowJsonEncode: When set to true, when attempting to encode a Redacted instance into JSON, it will fail with an error. This is useful when the wrapped schema is sensitive and should not be exposed in JSON.

See

Signature

declare function Redacted<S extends Constraint>(value: S, options?: {
readonly disallowJsonEncode?: boolean;
readonly label?: string;
}): Redacted<S>

Decodes a value and wraps it in Redacted<A>. Unlike Redacted which expects the input to already be a Redacted instance, this schema decodes the raw value and wraps it.

See

  • Redacted for schemas whose input is already a Redacted value.

Signature

declare function RedactedFromValue<S extends Constraint>(value: S, options?: {
readonly disallowEncode?: boolean;
readonly label?: string;
}): RedactedFromValue<S>
Since v4.0.0

Schema for JavaScript RegExp objects.

Details

The default JSON serializer encodes a RegExp as { source, flags }.

Signature

declare const RegExp: RegExp
Since v4.0.0

Schema for Result<A, E> values.

Signature

declare function Result<A extends Constraint, E extends Constraint>(success: A, failure: E): Result<A, E>

Schema for canonical scoped IPv6 literals such as fe80::1%eth0.

Signature

declare const ScopedIpv6Literal: ScopedIpv6Literal

Schema for scoped IPv6 literals decoded from strings, normalizing the address and numeric zones.

Signature

declare const ScopedIpv6LiteralFromString: ScopedIpv6LiteralFromString
Since v4.0.0

Schema for already-constructed portable concrete socket addresses.

Signature

declare const SocketAddress: SocketAddress

Schema for a Standard Schema v1 failure result.

Details

The result contains an issues array where each issue has a message and an optional path made of property keys or keyed path segments.

Signature

declare const StandardSchemaV1FailureResult: Struct<{
readonly issues: $Array<Struct<{
readonly message: String;
readonly path: optional<$Array<Union<readonly [Union<...>, Struct<...>]>>>;
}>>;
}>
Since v4.0.0

Schema for string values. Validates that the input is typeof "string".

Signature

declare const String: String

Schema for string & {}. Validates that the input is typeof "string".

When to use

Use with Union and Literals when a value may be any string and known literals should stay available for editor autocomplete.

Details

string & {} stays alongside string literals in a union, so editors keep suggesting those literals. Any string still passes validation. Read the literals from the Literals member.

See

  • String for a schema whose type is plain string.
  • Literals for the known literals to include in the union.

Signature

declare const StringForLiteralAutocomplete: StringForLiteralAutocomplete

Example Suggesting known HTTP methods

import { Schema } from "effect"
const Method = Schema.Union([
Schema.StringForLiteralAutocomplete,
Schema.Literals(["GET", "POST"])
])
// Type: "GET" | "POST" | (string & {})
Method.make("PATCH") // => "PATCH"
Method.members[1].literals // => ["GET", "POST"]

Decodes a base64 (RFC4648) encoded string into a UTF-8 string.

Details

Decoding:

  • A valid base64 encoded string is decoded as a UTF-8 string.

Encoding:

  • A string is encoded as a base64-encoded string.

Signature

declare const StringFromBase64: StringFromBase64

Decodes a base64 (URL) encoded string into a UTF-8 string.

Details

Decoding:

  • A valid base64 (URL) encoded string is decoded as a UTF-8 string.

Encoding:

  • A string is encoded as a base64 (URL) encoded string.

Signature

declare const StringFromBase64Url: StringFromBase64Url

Decodes a hex encoded string into a UTF-8 string.

Details

Decoding:

  • A valid hex encoded string is decoded as a UTF-8 string.

Encoding:

  • A string is encoded as a hex string.

Signature

declare const StringFromHex: StringFromHex

Decodes a URI component encoded string into a UTF-8 string. Can be used to store data in a URL.

Details

Decoding:

  • A valid URI component encoded string is decoded as a UTF-8 string.

Encoding:

  • A string is encoded as a URI component encoded string.

Signature

declare const StringFromUriComponent: StringFromUriComponent

Example Decoding URI component strings

import { Schema } from "effect"
const PaginationSchema = Schema.Struct({
maxItemPerPage: Schema.Number,
page: Schema.Number
})
const UrlSchema = Schema.StringFromUriComponent.pipe(
Schema.decodeTo(Schema.fromJsonString(PaginationSchema))
)
Schema.encodeSync(UrlSchema)({ maxItemPerPage: 10, page: 1 }) // => "%7B%22maxItemPerPage%22%3A10%2C%22page%22%3A1%7D"
Since v4.0.0

Schema for symbol values. Validates that the input is typeof "symbol".

See

Signature

declare const Symbol: Symbol
Since v3.10.0

Schema for DateTime.TimeZone values.

Details

Default JSON serializer:

  • encodes DateTime.TimeZone as a string (IANA identifier or offset like +03:00)

Signature

declare const TimeZone: TimeZone

Schema that parses a time zone string into a DateTime.TimeZone.

Details

Decoding:

  • A string (IANA identifier or offset like +03:00) is decoded as a DateTime.TimeZone.

Encoding:

  • A DateTime.TimeZone is encoded as a string.

Signature

declare const TimeZoneFromString: TimeZoneFromString

Schema for DateTime.TimeZone.Named values.

Details

Default JSON serializer:

  • encodes DateTime.TimeZone.Named as a string (IANA time zone identifier)

Signature

declare const TimeZoneNamed: TimeZoneNamed

Schema that parses an IANA time zone identifier string into a DateTime.TimeZone.Named.

Details

Decoding:

  • A string is decoded as a DateTime.TimeZone.Named.

Encoding:

  • A DateTime.TimeZone.Named is encoded as a string.

Signature

declare const TimeZoneNamedFromString: TimeZoneNamedFromString

Schema for DateTime.TimeZone.Offset values.

Details

Default JSON serializer:

  • encodes DateTime.TimeZone.Offset as a number (offset in milliseconds)

Signature

declare const TimeZoneOffset: TimeZoneOffset
Since v4.0.0

Creates a recursive schema for a Tree of values described by node. The resulting schema accepts a single node value, an array of trees, or an object whose values are trees.

Signature

declare function Tree<S extends Constraint>(node: S): Union<readonly [S, $Array<suspend<Codec<Tree<S["Type"]>, Tree<S["Encoded"]>, S["DecodingServices"], S["EncodingServices"]>>>, $Record<String, suspend<Codec<Tree<S["Type"]>, Tree<S["Encoded"]>, S["DecodingServices"], S["EncodingServices"]>>>]>
Since v3.10.0

Schema that trims whitespace from a string.

Details

Decoding:

  • A string is decoded as a string with no leading or trailing whitespaces.

Encoding:

  • The trimmed string is encoded as is.

Signature

declare const Trim: Trim
Since v3.10.0

Schema for strings that contains no leading or trailing whitespaces.

Signature

declare const Trimmed: Trimmed

Schema for JavaScript Uint8Array objects.

Details

Default JSON serializer:

The default JSON serializer encodes Uint8Array as a Base64 encoded string.

Signature

declare const Uint8Array: Uint8Array

Schema that decodes a base64 encoded string into a Uint8Array.

Details

Decoding:

  • A valid base64 encoded string is decoded as a Uint8Array.

Encoding:

  • A Uint8Array is encoded as a base64-encoded string.

Signature

declare const Uint8ArrayFromBase64: Uint8ArrayFromBase64

Schema that decodes a base64 (URL) encoded string into a Uint8Array.

Details

Decoding:

  • A valid base64 (URL) encoded string is decoded as a Uint8Array.

Encoding:

  • A Uint8Array is encoded as a base64 (URL) encoded string.

Signature

declare const Uint8ArrayFromBase64Url: Uint8ArrayFromBase64Url

Schema that decodes a hex encoded string into a Uint8Array.

Details

Decoding:

  • A valid hex encoded string is decoded as a Uint8Array.

Encoding:

  • A Uint8Array is encoded as a hex encoded string.

Signature

declare const Uint8ArrayFromHex: Uint8ArrayFromHex
Since v3.10.0

Schema for the undefined literal. Validates that the input is strictly undefined.

See

Signature

declare const Undefined: Undefined
Since v4.0.0

Schema for already-constructed Unix-domain filesystem addresses.

Signature

declare const UnixPathAddress: UnixPathAddress

Schema for Unix-domain filesystem addresses encoded as opaque path strings.

Signature

declare const UnixPathAddressFromString: UnixPathAddressFromString
Since v3.10.0

Schema for the unknown type. Accepts any value without validation.

When to use

Use as a top schema when you need to accept any input while preserving TypeScript's unknown safety at use sites.

See

  • Any for the any variant.

Signature

declare const Unknown: Unknown
Since v4.0.0

Schema for JavaScript URL objects.

Details

Default JSON serializer:

  • encodes URL as a string

Signature

declare const URL: URL

Schema that decodes a string into a URL.

Details

Decoding:

  • A valid URL string is decoded as a URL

Encoding:

  • A URL is encoded as a string

Signature

declare const URLFromString: URLFromString

UrlParams

unstable
Since v4.0.0

Schema for HTTP URL parameters.

Details

The encoded representation is an array of string key-value tuples.

Signature

declare const UrlParams: UrlParams

Schema for JavaScript URLSearchParams objects.

Details

The default JSON serializer encodes a URLSearchParams as a query string.

Signature

declare const URLSearchParams: URLSearchParams
Since v3.10.0

Schema for a TypeScript void return value.

When to use

Use when you need to model the return value of a function, RPC, or endpoint whose result is intentionally ignored.

Details

Runtime parsing accepts any present value and discards it, producing undefined. The public decoded and encoded TypeScript representation remains void, so typed construction, decoding, and encoding APIs are still modeled as void.

See

  • Undefined for a schema that matches only the exact undefined value.

Signature

declare const Void: Void

Transforming

compose

interface
Since v3.10.0

Type-level representation returned by decodeTo without a custom transformation.

Signature

interface compose<To extends Constraint, From extends Constraint> extends decodeTo<To, From> {
constructor(_: never);
}
Since v4.0.0

Applies a transformation to a schema, creating a new schema with the same type but transformed encoding/decoding.

When to use

Use when the decoded type stays the same and the transformation only normalizes values during encoding and decoding.

Details

Call it with a transformation object and then pipe a schema into the returned function. The resulting schema keeps the same Type and Encoded types as the source schema, while applying the transformation during both decoding and encoding.

Internally this uses toType(self) as the target schema and combines service requirements from the source schema and the transformation.

Gotchas

Use decodeTo instead when the transformation should change the decoded type. For this helper, both transformation getters operate on S["Type"] values.

Signature

declare function decode<S extends Constraint, RD = never, RE = never>(transformation: {
readonly decode: Getter<S["Type"], S["Type"], RD>;
readonly encode: Getter<S["Type"], S["Type"], RE>;
}): (self: S) => decodeTo<toType<S>, S, RD, RE>

Example Trimming string values during encoding/decoding

import { Schema, SchemaGetter } from "effect"
const Trimmed = Schema.String.pipe(
Schema.decode({
decode: SchemaGetter.transform((s) => s.trim()),
encode: SchemaGetter.transform((s) => s.trim())
})
)
Schema.decodeUnknownSync(Trimmed)(" hello ") // => "hello"
Since v4.0.0

Creates a schema that transforms from a source schema to a target schema.

When to use

Use when decoding should change the schema's decoded type or encoded shape, with an optional custom bidirectional transformation.

Details

Call it with the target schema to and then pipe the source schema from into the returned function. The resulting schema decodes from From["Encoded"] to To["Type"] and encodes from To["Type"] back to From["Encoded"].

When no transformation is provided, SchemaTransformation.passthrough() is used, so From["Type"] must already be compatible with To["Encoded"]. The resulting schema combines decoding and encoding services from both schemas and any custom transformation.

Gotchas

In a custom transformation, decode maps From["Type"] to To["Encoded"] and is used on the encoding path, while encode maps To["Encoded"] to From["Type"] and is used on the decoding path.

Signature

declare function decodeTo<To extends Constraint>(to: To): <From extends Constraint>(from: From) => compose<To, From>
declare function decodeTo<To extends Constraint, From extends Constraint, RD = never, RE = never>(to: To, transformation: {
readonly decode: Getter<NoInfer<To["Encoded"]>, NoInfer<From["Type"]>, RD>;
readonly encode: Getter<NoInfer<From["Type"]>, NoInfer<To["Encoded"]>, RE>;
}): (from: From) => decodeTo<To, From, RD, RE>

Example Transforming strings to numbers with a schema transformation

import { Schema, SchemaGetter } from "effect"
const NumberFromString = Schema.String.pipe(
Schema.decodeTo(
Schema.Number,
{
decode: SchemaGetter.transform((s) => Number(s)),
encode: SchemaGetter.transform((n) => String(n))
}
)
)
Schema.decodeUnknownSync(NumberFromString)("123") // => 123

decodeTo

interface
Since v4.0.0

Type-level representation returned by decodeTo.

Signature

interface decodeTo<To extends Constraint, From extends Constraint, RD = never, RE = never> extends BottomLazy<To["ast"], decodeTo<To, From, RD, RE>, To["~type.parameters"], To["~type.mutability"], To["~type.optionality"], To["~type.constructor.default"], From["~encoded.mutability"], From["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": To["~type.make"];
readonly "~type.make.in": To["~type.make.in"];
readonly DecodingServices: RD | To["DecodingServices"] | From["DecodingServices"];
readonly Encoded: From["Encoded"];
readonly EncodingServices: RE | To["EncodingServices"] | From["EncodingServices"];
readonly from: From;
readonly Iso: To["Iso"];
readonly to: To;
readonly Type: To["Type"];
}
Since v4.0.0

Applies a transformation to a schema's encoded type, creating a new schema where encoding/decoding operate on S["Encoded"] rather than S["Type"].

Details

The decode getter maps S["Encoded"] โ†’ S["Encoded"] (applied during decoding), and the encode getter maps S["Encoded"] โ†’ S["Encoded"] (applied during encoding).

Signature

declare function encode<S extends Constraint, RD = never, RE = never>(transformation: {
readonly decode: Getter<S["Encoded"], S["Encoded"], RD>;
readonly encode: Getter<S["Encoded"], S["Encoded"], RE>;
}): (self: S) => decodeTo<S, toEncoded<S>, RD, RE>

Example Upper-casing encoded strings

import { Schema, SchemaGetter } from "effect"
const UpperFromLower = Schema.String.pipe(
Schema.encode({
decode: SchemaGetter.transform((s: string) => s.toLowerCase()),
encode: SchemaGetter.transform((s: string) => s.toUpperCase())
})
)
Schema.encodeSync(UpperFromLower)("hello") // => "HELLO"

Renames struct keys in the encoded form without changing the decoded type.

Details

Takes a partial mapping { decodedKey: encodedKey } and produces a transformation schema that decodes from the renamed keys and encodes back to the renamed keys. Keys not present in the mapping are left unchanged. If two existing fields would produce the same encoded key, construction fails.

Signature

declare function encodeKeys<S extends Constraint & {
readonly fields: Fields;
}, M extends { [K in string | number | symbol]: PropertyKey }>(mapping: M): (self: S) => encodeKeys<S, M>

Example

import { Schema } from "effect"
const Person = Schema.Struct({ name: Schema.String, age: Schema.Number })
const Encoded = Person.pipe(Schema.encodeKeys({ name: "full_name" }))
// Decodes { full_name: "Alice", age: 30 } โ†’ { name: "Alice", age: 30 }
Schema.decodeUnknownSync(Encoded)({ full_name: "Alice", age: 30 }) // => { name: "Alice", age: 30 }

encodeKeys

interface
Since v4.0.0

Type-level representation returned by encodeKeys.

Signature

interface encodeKeys<S extends Constraint & {
readonly fields: Struct.Fields;
}, M extends { [K in keyof S["fields"]]: PropertyKey }> extends decodeTo<S, Struct<{ [K in keyof S["fields"]]: toEncoded<S["fields"][K]> }>> {
constructor(_: never);
}
Since v4.0.0

Reverses a schema transformation so the encoded schema is supplied first.

When to use

Use to define a transformation by naming the encoded schema before the decoded schema.

Details

encodeTo(to)(from) is equivalent to to.pipe(decodeTo(from)). The from schema acts as the target decoded schema and to acts as the encoded source.

Signature

declare function encodeTo<To extends Constraint>(to: To): <From extends Constraint>(from: From) => compose<From, To>
declare function encodeTo<To extends Constraint, From extends Constraint, RD = never, RE = never>(to: To, transformation: {
readonly decode: Getter<NoInfer<From["Encoded"]>, NoInfer<To["Type"]>, RD>;
readonly encode: Getter<NoInfer<To["Type"]>, NoInfer<From["Encoded"]>, RE>;
}): (from: From) => decodeTo<From, To, RD, RE>

Example Encoding a number back to a string

import { Schema, SchemaGetter } from "effect"
const NumberFromString = Schema.Number.pipe(
Schema.encodeTo(Schema.String, {
decode: SchemaGetter.transform((s: string) => Number(s)),
encode: SchemaGetter.transform((n: number) => String(n))
})
)
Schema.decodeSync(NumberFromString)("42") // => 42
Since v4.0.0

Adds derived fields to a struct schema during decoding.

Details

Each new field is derived from the decoded struct value via a function that returns Option. On encoding the derived fields are stripped. This allows computed or enriched fields to live in the decoded type without appearing in the encoded form.

Signature

declare function extendTo<S extends Struct<Fields>, Fields extends Fields>(fields: Fields, derive: { [K in string | number | symbol]: (s: S["Type"]) => Option<Fields[K]["Type"]> }): (self: S) => decodeTo<Struct<{ [K in string | number | symbol]: { [K in string | number | symbol]: toType<S["fields"][K]> } & Fields[K] }>, S>

Example

import { Option, Schema } from "effect"
const Person = Schema.Struct({ first: Schema.String, last: Schema.String })
const Extended = Person.pipe(
Schema.extendTo(
{ fullName: Schema.String },
{ fullName: (p) => Option.some(`${p.first} ${p.last}`) }
)
)
const alice = Schema.decodeUnknownSync(Extended)({ first: "Alice", last: "Smith" })
alice.fullName // => "Alice Smith"
Since v4.0.0

Swaps the decoded and encoded sides of a schema.

When to use

Use to invert a schema transformation direction.

Details

Calling flip twice returns the original schema.

Signature

declare function flip<S extends Top>(schema: S): S extends flip<F> ? F["Rebuild"] : flip<S>

Example Flipping a number-from-string schema

import { Schema } from "effect"
// NumberFromString: decodes string โ†’ number
const flipped = Schema.flip(Schema.NumberFromString)
Schema.decodeSync(flipped)(42) // => "42"

flip

interface
Since v4.0.0

Type-level representation returned by flip.

Signature

interface flip<S extends Top> extends BottomLazy<SchemaAST.AST, flip<S>, ReadonlyArray<Constraint>, S["~encoded.mutability"], S["~encoded.optionality"], ConstructorDefault, S["~type.mutability"], S["~type.optionality"]> {
constructor(_: never);
readonly "~effect/Schema/flip": "~effect/Schema/flip";
readonly "~type.make": S["Encoded"];
readonly "~type.make.in": S["Encoded"];
readonly DecodingServices: S["EncodingServices"];
readonly Encoded: S["Type"];
readonly EncodingServices: S["DecodingServices"];
readonly Iso: S["Encoded"];
readonly schema: S;
readonly Type: S["Encoded"];
}
Since v3.10.0

Makes an array or tuple schema mutable, removing the readonly modifier.

Gotchas

This combinator does not support an encoding attached to the array or tuple node and throws if one is present. Encodings on element schemas are supported.

Signature

declare const mutable: mutableLambda

Example Defining mutable arrays

import { Schema } from "effect"
const schema = Schema.mutable(Schema.Array(Schema.Number))
// number[] (mutable)
type T = typeof schema.Type
const value: T = [1, 2]
value.push(3)
value // => [1, 2, 3]

mutable

interface
Since v3.10.0

Type-level representation returned by mutable.

Signature

interface mutable<S extends Constraint & {
readonly ast: SchemaAST.Arrays;
}> extends BottomLazy<S["ast"], mutable<S>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: { [K in string | number | symbol]: S["Encoded"][K] };
readonly EncodingServices: S["EncodingServices"];
readonly Iso: S["Iso"];
readonly schema: S;
readonly Type: { [K in string | number | symbol]: S["Type"][K] };
}

Overrides a schema's derived ISO codec with an explicit target codec.

When to use

Use to provide a custom ISO transformation when the default derivation is not appropriate.

Details

The resulting schema carries a custom Iso type parameter and uses the provided decode and encode getters to transform between the schema type and the target codec.

Signature

declare function overrideToCodecIso<S extends Constraint, Iso>(to: ConstraintCodec<Iso>, transformation: {
readonly decode: Getter<S["Type"], Iso>;
readonly encode: Getter<Iso, S["Type"]>;
}): (schema: S) => overrideToCodecIso<S, Iso>
Since v4.0.0

Type-level representation returned by overrideToCodecIso.

Signature

interface overrideToCodecIso<S extends Constraint, Iso> extends BottomLazy<S["ast"], overrideToCodecIso<S, Iso>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: S["DecodingServices"];
readonly Encoded: S["Encoded"];
readonly EncodingServices: S["EncodingServices"];
Iso: Iso;
readonly schema: S;
readonly Type: S["Type"];
}

Extracts the encoded-side schema: sets Type to equal the Encoded, discarding the decoding transformation path.

Signature

declare const toEncoded: toEncodedLambda

toEncoded

interface
Since v4.0.0

Type-level representation returned by toEncoded.

Signature

interface toEncoded<S extends Constraint> extends BottomLazy<SchemaAST.AST, toEncoded<S>, ReadonlyArray<Constraint>, S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["Encoded"];
readonly "~type.make.in": S["Encoded"];
readonly DecodingServices: never;
readonly Encoded: S["Encoded"];
readonly EncodingServices: never;
readonly Iso: S["Encoded"];
readonly schema: S;
readonly Type: S["Encoded"];
}
Since v4.0.0

Extracts the type-side schema: sets Encoded to equal the decoded Type, discarding the encoding transformation path.

Signature

declare const toType: toTypeLambda

toType

interface
Since v4.0.0

Type-level representation returned by toType.

Signature

interface toType<S extends Constraint> extends BottomLazy<S["ast"], toType<S>, S["~type.parameters"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]> {
constructor(_: never);
readonly "~type.make": S["~type.make"];
readonly "~type.make.in": S["~type.make.in"];
readonly DecodingServices: never;
readonly Encoded: S["Type"];
readonly EncodingServices: never;
readonly Iso: S["Iso"];
readonly schema: S;
readonly Type: S["Type"];
}

Utility Types

Bottom

interface
Since v4.0.0

Fully-parameterized base interface for schemas that can be extended directly by TypeScript classes.

When to use

Use as the base for concrete schema interfaces whose runtime values support class ... extends schema.

Details

Extends BottomWithoutNew with a construct signature that accepts never. The signature enables class extension without making ordinary schemas directly constructible.

See

Signature

interface Bottom<out T, out E, out RD, out RE, out Ast extends SchemaAST.AST, out Rebuild extends Top, out TypeMakeIn = T, out Iso = T, in out TypeParameters extends ReadonlyArray<Constraint> = readonly [], out TypeMake = TypeMakeIn, out TypeMutability extends Mutability = "readonly", out TypeOptionality extends Optionality = "required", out TypeConstructorDefault extends ConstructorDefault = "no-default", out EncodedMutability extends Mutability = "readonly", out EncodedOptionality extends Optionality = "required"> extends BottomWithoutNew<T, E, RD, RE, Ast, Rebuild, TypeMakeIn, Iso, TypeParameters, TypeMake, TypeMutability, TypeOptionality, TypeConstructorDefault, EncodedMutability, EncodedOptionality> {
constructor(_: never);
}

BottomLazy

interface
Since v4.0.0

Lazy Bottom variant for schemas that can be extended directly by TypeScript classes.

When to use

Use as the base for concrete lazy schema interfaces whose runtime values support class ... extends schema.

Details

Extends BottomLazyWithoutNew with a construct signature that accepts never. The signature enables class extension without making ordinary schemas directly constructible.

See

Signature

interface BottomLazy<out Ast extends SchemaAST.AST, out Rebuild extends Top, in out TypeParameters extends ReadonlyArray<Constraint> = readonly [], out TypeMutability extends Mutability = "readonly", out TypeOptionality extends Optionality = "required", out TypeConstructorDefault extends ConstructorDefault = "no-default", out EncodedMutability extends Mutability = "readonly", out EncodedOptionality extends Optionality = "required"> extends BottomLazyWithoutNew<Ast, Rebuild, TypeParameters, TypeMutability, TypeOptionality, TypeConstructorDefault, EncodedMutability, EncodedOptionality> {
constructor(_: never);
}
Since v4.0.0

Lazy BottomWithoutNew variant for schema implementations that compute their public views on demand.

When to use

Use as the base for lazy schema interfaces that provide a specialized construct signature.

Details

The laziness is purely type-level; runtime behavior is unchanged. BottomLazyWithoutNew keeps the structural operations inherited from BottomWithoutNew, but erases the expensive schema views to unknown. Concrete schema interfaces can then redeclare the precise views they expose. This keeps wide schemas such as Struct and Union cheaper when generic code reads a single view, while preserving their exact public types.

See

  • BottomWithoutNew for the fully parameterized schema interface when every view must be supplied directly.

Signature

interface BottomLazyWithoutNew<out Ast extends SchemaAST.AST, out Rebuild extends Top, in out TypeParameters extends ReadonlyArray<Constraint> = readonly [], out TypeMutability extends Mutability = "readonly", out TypeOptionality extends Optionality = "required", out TypeConstructorDefault extends ConstructorDefault = "no-default", out EncodedMutability extends Mutability = "readonly", out EncodedOptionality extends Optionality = "required"> extends BottomWithoutNew<unknown, unknown, unknown, unknown, Ast, Rebuild, unknown, unknown, TypeParameters, unknown, TypeMutability, TypeOptionality, TypeConstructorDefault, EncodedMutability, EncodedOptionality> {}
Since v4.0.0

Iso representation used for Cause schemas: an ordered array of CauseReasonIso values.

When to use

Use when working with the ISO shape of a Cause schema, such as toIso optics or codecs that expose a cause as its ordered array of encoded reasons.

See

  • Cause for constructing schemas for full Cause values
  • CauseReasonIso for the ISO shape of each array element

Signature

type CauseIso<E extends Constraint, D extends Constraint> = ReadonlyArray<CauseReasonIso<E, D>>
Since v4.0.0

Iso representation used for CauseReason schemas.

Details

Failures are represented with a Fail tag and encoded error, defects with a Die tag and encoded defect, and interrupts with an optional fiberId.

Signature

type CauseReasonIso<E extends Constraint, D extends Constraint> = {
readonly _tag: "Fail";
readonly error: E["Iso"];
} | {
readonly _tag: "Die";
readonly error: D["Iso"];
} | {
readonly _tag: "Interrupt";
readonly fiberId: number | undefined;
}
Since v4.0.0

Iso representation used for Chunk schemas: an array of element values using the element schema's Iso type.

When to use

Use when annotating type-level helpers that work with the readonly-array ISO shape of a Chunk schema.

See

  • Chunk for the schema interface and constructor that use this ISO representation

Signature

type ChunkIso<Value extends Constraint> = ReadonlyArray<Value["Iso"]>
Since v4.0.0

Iso representation used for Exit schemas.

Details

Successful exits are represented as { _tag: "Success", value }, while failed exits are represented as { _tag: "Failure", cause }.

Signature

type ExitIso<A extends Constraint, E extends Constraint, D extends Constraint> = {
readonly _tag: "Success";
readonly value: A["Iso"];
} | {
readonly _tag: "Failure";
readonly cause: CauseIso<E, D>;
}

GraphIso

type unstable
Since v4.0.0

Iso representation used for Graph schemas.

Signature

type GraphIso<T extends Graph_.Kind, Node extends Constraint, Edge extends Constraint> = EncodedGraph<Node["Iso"], Edge["Iso"], T>
Since v4.0.0

Iso representation used for HashMap schemas: an array of readonly [key, value] tuples using each entry schema's Iso type.

Signature

type HashMapIso<Key extends Constraint, Value extends Constraint> = ReadonlyArray<readonly [Key["Iso"], Value["Iso"]]>
Since v4.0.0

Iso representation used for HashSet schemas: an array of element values using the element schema's Iso type.

Signature

type HashSetIso<Value extends Constraint> = ReadonlyArray<Value["Iso"]>
Since v4.0.0

Iso representation used for Option schemas.

Details

None is represented as { _tag: "None" }, while Some is represented as { _tag: "Some", value } using the wrapped schema's Iso type.

Signature

type OptionIso<A extends Constraint> = {
readonly _tag: "None";
} | {
readonly _tag: "Some";
readonly value: A["Iso"];
}
Since v4.0.0

Iso representation used for ReadonlyMap schemas: an array of readonly [key, value] tuples using each entry schema's Iso type.

Signature

type ReadonlyMapIso<Key extends Constraint, Value extends Constraint> = ReadonlyArray<readonly [Key["Iso"], Value["Iso"]]>
Since v4.0.0

Iso representation used for ReadonlySet schemas: an array of element values using the element schema's Iso type.

Signature

type ReadonlySetIso<Value extends Constraint> = ReadonlyArray<Value["Iso"]>
Since v4.0.0

Iso representation used for Result schemas.

Details

Successful results are represented as { _tag: "Success", success }, while failed results are represented as { _tag: "Failure", failure }.

Signature

type ResultIso<A extends Constraint, E extends Constraint> = {
readonly _tag: "Success";
readonly success: A["Iso"];
} | {
readonly _tag: "Failure";
readonly failure: E["Iso"];
}

Returns a schema widened to the fully-parameterized Bottom interface, making all 14 type parameters visible to TypeScript.

Details

Normally, concrete schema interfaces (e.g. Schema<string>) hide most type parameters. revealBottom is useful when writing generic utilities that need to inspect or propagate the complete set of type parameters.

Signature

declare function revealBottom<S extends Top>(bottom: S): Bottom<S["Type"], S["Encoded"], S["DecodingServices"], S["EncodingServices"], S["ast"], S["Rebuild"], S["~type.make.in"], S["Iso"], S["~type.parameters"], S["~type.make"], S["~type.mutability"], S["~type.optionality"], S["~type.constructor.default"], S["~encoded.mutability"], S["~encoded.optionality"]>

Example Inspecting all type parameters of a schema

import { Schema } from "effect"
const schema = Schema.String
// Widen to Bottom to access all 14 type parameters
const bottom = Schema.revealBottom(schema)
// `bottom` now exposes Type, Encoded, DecodingServices, EncodingServices,
// ast, Rebuild, ~type.make.in, Iso, ~type.parameters, etc.
type T = typeof bottom["Type"] // string
type E = typeof bottom["Encoded"] // string

Returns a codec widened to the full Codec interface, prompting TypeScript to infer all four type parameters (T, E, RD, RE).

Details

When a schema is stored in a variable typed as Schema<T> or Top, the encoded type and service requirements are erased. Passing the value through revealCodec recovers those parameters without any runtime cost.

Signature

declare function revealCodec<T, E, RD, RE>(codec: Codec<T, E, RD, RE>): Codec<T, E, RD, RE>

Example Recovering encoded type from a schema variable

import { Schema } from "effect"
const schema: Schema.Schema<number> = Schema.NumberFromString
// Without revealCodec, Encoded is unknown
const codec = Schema.revealCodec(schema)
type Enc = typeof codec["Encoded"] // string

Validation

Since v4.0.0

Validates that a string is valid Base64 encoded data.

Details

JSON Schema:

This check corresponds to a pattern constraint in JSON Schema that matches Base64 format.

Arbitrary:

During arbitrary generation, this applies a patterns constraint to ensure generated strings match the Base64 pattern.

Signature

declare function isBase64(annotations?: Filter): Filter<string>

Validates that a string is valid Base64URL encoded data (Base64 with URL-safe characters).

Details

JSON Schema:

This check corresponds to a pattern constraint in JSON Schema that matches Base64URL format.

Arbitrary:

During arbitrary generation, this applies a patterns constraint to ensure generated strings match the Base64URL pattern.

Signature

declare function isBase64Url(annotations?: Filter): Filter<string>

Validates that a number is within a specified range. The range boundaries can be inclusive or exclusive based on the provided options.

Details

JSON Schema:

This check corresponds to minimum/maximum or exclusiveMinimum/exclusiveMaximum constraints in JSON Schema, depending on the options provided.

Arbitrary:

During arbitrary generation, this applies minimum and maximum constraints with optional exclusiveMinimum and exclusiveMaximum flags to ensure generated numbers fall within the specified range.

Signature

declare const isBetween: (options: {
readonly exclusiveMaximum?: boolean;
readonly exclusiveMinimum?: boolean;
readonly maximum: number;
readonly minimum: number;
}, annotations?: Annotations.Filter) => SchemaAST.Filter<number>

Validates that a BigDecimal is within a specified range.

Details

The minimum and maximum boundaries are inclusive by default. Pass exclusiveMinimum or exclusiveMaximum to exclude either boundary.

Signature

declare const isBetweenBigDecimal: (options: {
readonly exclusiveMaximum?: boolean;
readonly exclusiveMinimum?: boolean;
readonly maximum: BigDecimal_.BigDecimal;
readonly minimum: BigDecimal_.BigDecimal;
}, annotations?: Annotations.Filter) => SchemaAST.Filter<BigDecimal_.BigDecimal>

Validates that a BigInt is within a specified range. The range boundaries can be inclusive or exclusive based on the provided options.

Details

Arbitrary:

During arbitrary generation, this applies the specified lower and upper bounds.

Signature

declare const isBetweenBigInt: (options: {
readonly exclusiveMaximum?: boolean;
readonly exclusiveMinimum?: boolean;
readonly maximum: bigint;
readonly minimum: bigint;
}, annotations?: Annotations.Filter) => SchemaAST.Filter<bigint>

Validates that a string's Unicode code point count is within the specified inclusive range.

Details

Bounds must be finite; they are rounded down and clamped to zero. Equal bounds require an exact count. This check corresponds to minLength and maxLength in JSON Schema and guides arbitrary generation by code point count.

Gotchas

Code points are not grapheme clusters: combining marks and joined emoji can contribute multiple code points to one visible character. Unpaired UTF-16 surrogates count as one code point each. This check does not normalize strings.

See

Signature

declare function isBetweenCodePoints(minimum: number, maximum: number, annotations?: Filter): Filter<string>

Validates that a Date is within a specified range. The range boundaries can be inclusive or exclusive based on the provided options.

Details

JSON Schema:

This check does not have a direct JSON Schema equivalent, as JSON Schema validates date strings, not Date objects.

Arbitrary:

During arbitrary generation, this applies the specified lower and upper bounds.

Signature

declare const isBetweenDate: (options: {
readonly exclusiveMaximum?: boolean;
readonly exclusiveMinimum?: boolean;
readonly maximum: globalThis.Date;
readonly minimum: globalThis.Date;
}, annotations?: Annotations.Filter) => SchemaAST.Filter<globalThis.Date>

Validates that a value's length is within the specified range. Works with strings and arrays.

Details

JSON Schema:

Both bounds must be finite; they are rounded down and clamped to zero. Arrays use the same bounds for minItems and maxItems. JavaScript counts UTF-16 code units while JSON Schema counts Unicode code points, so strings use Math.ceil(minimum / 2) for minLength and maximum for maxLength. These are the tightest bounds that cannot reject a string accepted by this check.

Arbitrary:

During arbitrary generation, this applies minLength and maxLength constraints to ensure generated strings or arrays have a length within the specified range.

Signature

declare function isBetweenLength(minimum: number, maximum: number, annotations?: Filter): Filter<{
readonly length: number;
}>

Validates that an object contains between minimum and maximum properties (inclusive). This includes both string and symbol keys when counting properties.

Details

Both bounds must be finite; they are rounded down and clamped to zero.

JSON Schema:

This check corresponds to minProperties and maxProperties in JSON Schema. Effect applies the check to the decoded object, while JSON Schema applies it to the original input. Defaults, excess-property handling, and property transformations can therefore produce different results.

Arbitrary:

During arbitrary generation, this applies node-local minProperties and maxProperties constraints.

Signature

declare function isBetweenProperties(minimum: number, maximum: number, annotations?: Filter): Filter<object>

Validates that a value's size is within the specified range. Works with values that have a size property, such as Set or Map.

Details

Both bounds must be finite; they are rounded down and clamped to zero.

JSON Schema:

This check does not have a direct JSON Schema equivalent, as it applies to values with a size property rather than standard JSON Schema types.

Arbitrary:

During arbitrary generation, this applies node-local minSize and maxSize constraints.

Signature

declare function isBetweenSize(minimum: number, maximum: number, annotations?: Filter): Filter<{
readonly size: number;
}>

Validates that the first character of a string is unchanged by toUpperCase().

Details

Empty strings pass. Strings whose first character has no lowercase form, such as a digit, punctuation mark, or whitespace, also pass.

Signature

declare function isCapitalized(annotations?: Filter): Filter<string>

Validates at runtime that a string ends with the specified literal suffix.

Details

RegExp metacharacters in the suffix are escaped in JSON Schema and arbitrary metadata. If the suffix begins with a low surrogate, the JSON Schema pattern omits that code unit so Unicode matching cannot reject a valid string.

Signature

declare function isEndingWith(endsWith: string, annotations?: Filter): Filter<string>
Since v4.0.0

Validates that a number is finite (not Infinity, -Infinity, or NaN).

Details

JSON Schema:

This check does not have a direct JSON Schema equivalent, but ensures the number is valid and finite.

Arbitrary:

During arbitrary generation, this applies a finite-number constraint.

Signature

declare const isFinite: (annotations?: Annotations.Filter) => SchemaAST.Filter<number>

Validates that a number is greater than the specified value (exclusive).

Details

JSON Schema:

This check corresponds to the exclusiveMinimum constraint in JSON Schema.

Arbitrary:

During arbitrary generation, this applies an exclusiveMinimum constraint to ensure generated numbers are greater than the specified value.

Signature

declare const isGreaterThan: (exclusiveMinimum: number, annotations?: Annotations.Filter) => SchemaAST.Filter<number>

Validates that a BigDecimal is greater than the specified value (exclusive).

Signature

declare const isGreaterThanBigDecimal: (exclusiveMinimum: BigDecimal_.BigDecimal, annotations?: Annotations.Filter) => SchemaAST.Filter<BigDecimal_.BigDecimal>

Validates that a BigInt is greater than the specified value (exclusive).

Details

Arbitrary:

During arbitrary generation, this applies an exclusive lower bound.

Signature

declare const isGreaterThanBigInt: (exclusiveMinimum: bigint, annotations?: Annotations.Filter) => SchemaAST.Filter<bigint>

Validates that a Date is greater than the specified value (exclusive).

Details

Arbitrary:

During arbitrary generation, this applies an exclusive lower bound.

Signature

declare const isGreaterThanDate: (exclusiveMinimum: globalThis.Date, annotations?: Annotations.Filter) => SchemaAST.Filter<globalThis.Date>

Validates that a number is greater than or equal to the specified value (inclusive).

Details

JSON Schema:

This check corresponds to the minimum constraint in JSON Schema.

Arbitrary:

During arbitrary generation, this applies a minimum constraint to ensure generated numbers are greater than or equal to the specified value.

Signature

declare const isGreaterThanOrEqualTo: (minimum: number, annotations?: Annotations.Filter) => SchemaAST.Filter<number>

Validates that a BigDecimal is greater than or equal to the specified value (inclusive).

Signature

declare const isGreaterThanOrEqualToBigDecimal: (minimum: BigDecimal_.BigDecimal, annotations?: Annotations.Filter) => SchemaAST.Filter<BigDecimal_.BigDecimal>

Validates that a BigInt is greater than or equal to the specified value (inclusive).

Details

Arbitrary:

During arbitrary generation, this applies an inclusive lower bound.

Signature

declare const isGreaterThanOrEqualToBigInt: (minimum: bigint, annotations?: Annotations.Filter) => SchemaAST.Filter<bigint>

Validates that a Date is greater than or equal to the specified date (inclusive).

Details

JSON Schema:

This check does not have a direct JSON Schema equivalent, as JSON Schema validates date strings, not Date objects.

Arbitrary:

During arbitrary generation, this applies an inclusive lower bound.

Signature

declare const isGreaterThanOrEqualToDate: (minimum: globalThis.Date, annotations?: Annotations.Filter) => SchemaAST.Filter<globalThis.Date>
Since v4.0.0

Validates that a string has the GUID / UUID textual shape.

When to use

Use when you need to accept dashed hexadecimal identifiers without enforcing UUID version or variant bits.

Details

This check accepts strings in the 8-4-4-4-12 hexadecimal form. JSON Schema output includes the corresponding pattern constraint and intentionally does not include format: "uuid" because GUID validation is looser than UUID validation.

Arbitrary:

During arbitrary generation, this applies a patterns constraint to ensure generated strings match the GUID pattern.

See

  • isUUID for strict UUID validation.

Signature

declare function isGUID(annotations?: Filter): Filter<string>

Validates at runtime that a string contains the specified literal substring.

Details

RegExp metacharacters in the substring are escaped in JSON Schema and arbitrary metadata. A leading low surrogate or trailing high surrogate is omitted from the JSON Schema pattern so Unicode matching cannot reject a valid string.

Signature

declare function isIncluding(includes: string, annotations?: Filter): Filter<string>
Since v4.0.0

Validates that a number is a safe integer (within the safe integer range that can be exactly represented in JavaScript).

Details

JSON Schema:

This check corresponds to type: "integer" with minimum: Number.MIN_SAFE_INTEGER and maximum: Number.MAX_SAFE_INTEGER in JSON Schema.

Arbitrary:

During arbitrary generation, this applies an integer constraint.

Signature

declare function isInt(annotations?: Filter): Filter<number>
Since v4.0.0

Validates that a number is a 32-bit signed integer (range: -2,147,483,648 to 2,147,483,647).

Details

JSON Schema:

This check corresponds to the format: "int32" constraint in OpenAPI 3.1, or minimum/maximum constraints in other JSON Schema targets.

Arbitrary:

During arbitrary generation, this applies integer and range constraints to ensure generated numbers are 32-bit signed integers.

Signature

declare function isInt32(annotations?: Filter): FilterGroup<number>

Validates that a number is less than the specified value (exclusive).

Details

JSON Schema:

This check corresponds to the exclusiveMaximum constraint in JSON Schema.

Arbitrary:

During arbitrary generation, this applies an exclusiveMaximum constraint to ensure generated numbers are less than the specified value.

Signature

declare const isLessThan: (exclusiveMaximum: number, annotations?: Annotations.Filter) => SchemaAST.Filter<number>

Validates that a BigDecimal is less than the specified value (exclusive).

Signature

declare const isLessThanBigDecimal: (exclusiveMaximum: BigDecimal_.BigDecimal, annotations?: Annotations.Filter) => SchemaAST.Filter<BigDecimal_.BigDecimal>

Validates that a BigInt is less than the specified value (exclusive).

Details

Arbitrary:

During arbitrary generation, this applies an exclusive upper bound.

Signature

declare const isLessThanBigInt: (exclusiveMaximum: bigint, annotations?: Annotations.Filter) => SchemaAST.Filter<bigint>

Validates that a Date is less than the specified value (exclusive).

Details

Arbitrary:

During arbitrary generation, this applies an exclusive upper bound.

Signature

declare const isLessThanDate: (exclusiveMaximum: globalThis.Date, annotations?: Annotations.Filter) => SchemaAST.Filter<globalThis.Date>

Validates that a number is less than or equal to the specified value (inclusive).

Details

JSON Schema:

This check corresponds to the maximum constraint in JSON Schema.

Arbitrary:

During arbitrary generation, this applies a maximum constraint to ensure generated numbers are less than or equal to the specified value.

Signature

declare const isLessThanOrEqualTo: (maximum: number, annotations?: Annotations.Filter) => SchemaAST.Filter<number>

Validates that a BigDecimal is less than or equal to the specified value (inclusive).

Signature

declare const isLessThanOrEqualToBigDecimal: (maximum: BigDecimal_.BigDecimal, annotations?: Annotations.Filter) => SchemaAST.Filter<BigDecimal_.BigDecimal>

Validates that a BigInt is less than or equal to the specified value (inclusive).

Details

Arbitrary:

During arbitrary generation, this applies an inclusive upper bound.

Signature

declare const isLessThanOrEqualToBigInt: (maximum: bigint, annotations?: Annotations.Filter) => SchemaAST.Filter<bigint>

Validates that a Date is less than or equal to the specified date (inclusive).

Details

JSON Schema:

This check does not have a direct JSON Schema equivalent, as JSON Schema validates date strings, not Date objects.

Arbitrary:

During arbitrary generation, this applies an inclusive upper bound.

Signature

declare const isLessThanOrEqualToDate: (maximum: globalThis.Date, annotations?: Annotations.Filter) => SchemaAST.Filter<globalThis.Date>

Validates that a string is unchanged by JavaScript's toLowerCase().

Details

This accepts empty strings and characters that do not have uppercase forms, such as digits, punctuation, and whitespace. It rejects strings that would change when lowercased.

Signature

declare function isLowercased(annotations?: Filter): Filter<string>

Validates that a string contains at most the specified number of Unicode code points.

Details

The bound must be finite; it is rounded down and clamped to zero. This check corresponds to maxLength in JSON Schema and guides arbitrary generation by code point count.

Gotchas

Code points are not grapheme clusters: combining marks and joined emoji can contribute multiple code points to one visible character. Unpaired UTF-16 surrogates count as one code point each. This check does not normalize strings.

See

Signature

declare function isMaxCodePoints(maxCodePoints: number, annotations?: Filter): Filter<string>

Validates that a value has at most the specified length. Works with strings and arrays.

Details

JSON Schema:

The bound must be finite; it is rounded down and clamped to zero. This check corresponds to maxItems for arrays. Strings use the same bound for maxLength, which cannot reject a string accepted by this check because a string has no more code points than UTF-16 code units.

Arbitrary:

During arbitrary generation, this applies a maxLength constraint to ensure generated strings or arrays have at most the required length.

Signature

declare function isMaxLength(maxLength: number, annotations?: Filter): Filter<{
readonly length: number;
}>

Validates that an object contains at most the specified number of properties. This includes both string and symbol keys when counting properties.

Details

The bound must be finite; it is rounded down and clamped to zero.

JSON Schema:

This check corresponds to maxProperties in JSON Schema. Effect applies the check to the decoded object, while JSON Schema applies it to the original input. Excess-property handling and property transformations can therefore produce different results.

Arbitrary:

During arbitrary generation, this applies a node-local maxProperties constraint.

Signature

declare function isMaxProperties(maxProperties: number, annotations?: Filter): Filter<object>

Validates that a value has at most the specified size. Works with values that have a size property, such as Set or Map.

Details

The bound must be finite; it is rounded down and clamped to zero.

JSON Schema:

This check does not have a direct JSON Schema equivalent, as it applies to values with a size property rather than standard JSON Schema types.

Arbitrary:

During arbitrary generation, this applies a node-local maxSize constraint.

Signature

declare function isMaxSize(maxSize: number, annotations?: Filter): Filter<{
readonly size: number;
}>

Validates that a string contains at least the specified number of Unicode code points.

Details

The bound must be finite; it is rounded down and clamped to zero. This check corresponds to minLength in JSON Schema and guides arbitrary generation by code point count.

Gotchas

Code points are not grapheme clusters: combining marks and joined emoji can contribute multiple code points to one visible character. Unpaired UTF-16 surrogates count as one code point each. This check does not normalize strings.

See

Signature

declare function isMinCodePoints(minCodePoints: number, annotations?: Filter): Filter<string>

Validates that a value has at least the specified length. Works with strings and arrays.

Details

JSON Schema:

The bound must be finite; it is rounded down and clamped to zero. For arrays, this check corresponds to minItems. JavaScript counts UTF-16 code units while JSON Schema counts Unicode code points, so strings use minLength: Math.ceil(minLength / 2), the tightest lower bound that cannot reject a string accepted by this check.

Arbitrary:

During arbitrary generation, this applies a minLength constraint to ensure generated strings or arrays have at least the required length.

Signature

declare function isMinLength(minLength: number, annotations?: Filter): Filter<{
readonly length: number;
}>

Example Checking minimum length

import { Schema } from "effect"
const NonEmptyStringSchema = Schema.String.check(Schema.isMinLength(1))
const NonEmptyArraySchema = Schema.Array(Schema.Number).check(Schema.isMinLength(1))
Schema.is(NonEmptyStringSchema)("a") // => true
Schema.is(NonEmptyArraySchema)([1]) // => true

Validates that an object contains at least the specified number of properties. This includes both string and symbol keys when counting properties.

Details

The bound must be finite; it is rounded down and clamped to zero.

JSON Schema:

This check corresponds to minProperties in JSON Schema. Effect applies the check to the decoded object, while JSON Schema applies it to the original input. Defaults and property transformations can therefore produce different results.

Arbitrary:

During arbitrary generation, this applies a node-local minProperties constraint.

Signature

declare function isMinProperties(minProperties: number, annotations?: Filter): Filter<object>

Validates that a value has at least the specified size. Works with values that have a size property, such as Set or Map.

Details

The bound must be finite; it is rounded down and clamped to zero.

JSON Schema:

This check does not have a direct JSON Schema equivalent, as it applies to values with a size property rather than standard JSON Schema types.

Arbitrary:

During arbitrary generation, this applies a node-local minSize constraint.

Signature

declare function isMinSize(minSize: number, annotations?: Filter): Filter<{
readonly size: number;
}>

Validates that a number is a multiple of the specified divisor.

Details

JSON Schema:

This check corresponds to the multipleOf constraint in JSON Schema. Negative divisors are normalized to their absolute value because JSON Schema requires multipleOf to be positive.

Gotchas

Throws a RangeError when divisor is zero or is not finite.

Signature

declare function isMultipleOf(divisor: number, annotations?: Filter): Filter<number>

Validates that a value has at least one element. Works with strings and arrays. This is equivalent to isMinLength(1).

Details

JSON Schema:

This check corresponds to the minLength: 1 constraint for strings or the minItems: 1 constraint for arrays in JSON Schema.

Arbitrary:

During arbitrary generation, this applies a minLength: 1 constraint to ensure generated strings or arrays are non-empty.

Signature

declare function isNonEmpty(annotations?: Filter): Filter<{
readonly length: number;
}>

Validates that a string matches the specified regular expression pattern.

Details

JSON Schema:

Unless annotations override toJsonSchema, JSON Schema receives a pattern only when the JavaScript RegExp uses the Unicode flag and its other flags are d, g, or y. Sticky patterns are anchored at the start of the string.

Arbitrary:

During arbitrary generation, this applies a patterns constraint to ensure generated strings match the specified RegExp pattern.

Signature

declare function isPattern(regExp: RegExp, annotations?: Filter): Filter<string>

Validates that every own property key of an object satisfies the encoded side of the provided key schema.

Details

This check uses Reflect.ownKeys, so symbol keys are validated in addition to string property names.

JSON Schema: This check corresponds to propertyNames in JSON Schema. Effect checks the decoded object's keys, including symbols, while JSON Schema checks the string names in the original input. Property transformations and excess-property handling can therefore produce different results.

Signature

declare function isPropertyNames(keySchema: Constraint, annotations?: Filter): Filter<object>

Validates at runtime that a string starts with the specified literal prefix.

Details

RegExp metacharacters in the prefix are escaped in JSON Schema and arbitrary metadata. If the prefix ends with a high surrogate, the JSON Schema pattern omits that code unit so Unicode matching cannot reject a valid string.

Signature

declare function isStartingWith(startsWith: string, annotations?: Filter): Filter<string>

Validates that a string is a signed base-10 integer literal for Effect's BigInt string encoding.

Details

The check uses the pattern ^-?\d+$. It does not accept leading +, decimal points, exponent notation, separators, or non-decimal inputs such as hexadecimal strings.

JSON Schema: This check corresponds to a pattern constraint with the same signed base-10 integer pattern.

Signature

declare function isStringBigInt(annotations?: Filter): Filter<string>

Validates that a string represents a finite number.

Details

JSON Schema:

This check corresponds to a pattern constraint in JSON Schema that matches strings representing finite numbers.

Arbitrary:

During arbitrary generation, this applies a patterns constraint to ensure generated strings match the number string pattern.

Signature

declare function isStringFinite(annotations?: Filter): Filter<string>

Validates that a string has the Symbol(description) format used by Effect's symbol string encoding.

Details

The check uses the pattern ^Symbol\((.*)\)$. It is not a general test for whether a string can be passed to JavaScript's Symbol() function.

Signature

declare function isStringSymbol(annotations?: Filter): Filter<string>

Validates that a string has no leading or trailing whitespace.

Details

JSON Schema:

This check corresponds to a pattern constraint in JSON Schema that matches strings without leading or trailing whitespace.

Arbitrary:

During arbitrary generation, this applies a patterns constraint to ensure generated strings match the trimmed pattern.

Signature

declare function isTrimmed(annotations?: Filter): Filter<string>
Since v4.0.0

Validates that a number is a 32-bit unsigned integer (range: 0 to 4,294,967,295).

Details

JSON Schema:

This check corresponds to the format: "uint32" constraint in OpenAPI 3.1, or minimum/maximum constraints in other JSON Schema targets.

Arbitrary:

During arbitrary generation, this applies integer and range constraints to ensure generated numbers are 32-bit unsigned integers.

Signature

declare function isUint32(annotations?: Filter): FilterGroup<number>
Since v4.0.0

Validates that a string is a valid ULID (Universally Unique Lexicographically Sortable Identifier).

Details

JSON Schema:

This check corresponds to a pattern constraint in JSON Schema that matches the ULID format.

Arbitrary:

During arbitrary generation, this applies a patterns constraint to ensure generated strings match the ULID pattern.

Signature

declare function isULID(annotations?: Filter): Filter<string>

Validates that the first character of a string is unchanged by toLowerCase().

Details

Empty strings pass. Strings whose first character has no uppercase form, such as a digit, punctuation mark, or whitespace, also pass.

Signature

declare function isUncapitalized(annotations?: Filter): Filter<string>
Since v4.0.0

Validates that all items in an array are unique according to Effect equality.

Details

JSON Schema: This check corresponds to the uniqueItems: true constraint in JSON Schema.

Arbitrary: During arbitrary generation, this applies a node-local identity selector for constructive uniqueness using Effect equality.

Signature

declare function isUnique<T>(annotations?: Filter): Filter<readonly Array<T>>

Validates that all first elements in an array of key-value tuples are unique according to Effect equality.

Details

Arbitrary: During arbitrary generation, this projects each entry to its key for constructive uniqueness.

JSON Schema: JSON Schema has no equivalent constraint, so this check is omitted from generated documents.

See

  • isUnique for validating uniqueness of complete array elements

Signature

declare function isUniqueKey<Key, Value>(annotations?: Filter): Filter<readonly Array<readonly [Key, Value]>>

Validates that a string is unchanged by JavaScript's toUpperCase().

Details

This accepts empty strings and characters that do not have lowercase forms, such as digits, punctuation, and whitespace. It rejects strings that would change when uppercased.

Signature

declare function isUppercased(annotations?: Filter): Filter<string>
Since v4.0.0

Validates that a string is a strict Universally Unique Identifier (UUID).

When to use

Use when you need UUID semantics, including version and RFC variant bits, rather than only the dashed hexadecimal shape.

Details

Without a version argument, this accepts UUID versions 1 through 8, the nil UUID (00000000-0000-0000-0000-000000000000), and the max UUID (ffffffff-ffff-ffff-ffff-ffffffffffff). With a version argument, this accepts only UUIDs with that version and RFC variant bits; nil and max UUIDs are not versioned UUIDs and do not match version-specific checks.

JSON Schema:

This check corresponds to a pattern constraint in JSON Schema that matches UUID format, and includes a format: "uuid" annotation.

Arbitrary:

During arbitrary generation, this applies a patterns constraint to ensure generated strings match the UUID pattern.

See

  • isGUID for shape-only GUID validation.

Signature

declare function isUUID(version?: 1 | 2 | 5 | 3 | 4 | 6 | 8 | 7, annotations?: Filter): Filter<string>

Creates an inclusive or exclusive range check for any ordered type from an Order.Order instance.

Signature

declare function makeIsBetween<T>(deriveOptions: {
readonly annotate?: (options: {
readonly exclusiveMaximum?: boolean;
readonly exclusiveMinimum?: boolean;
readonly maximum: T;
readonly minimum: T;
}) => Filter;
readonly formatter?: Formatter<T, string>;
readonly order: Order<T>;
}): (options: {
readonly exclusiveMaximum?: boolean;
readonly exclusiveMinimum?: boolean;
readonly maximum: T;
readonly minimum: T;
}, annotations?: Filter) => Filter<T>

Creates a greater-than (>) check for any ordered type from an Order.Order instance.

Signature

declare function makeIsGreaterThan<T>(options: {
readonly annotate?: (exclusiveMinimum: T) => Filter;
readonly formatter?: Formatter<T, string>;
readonly order: Order<T>;
}): (exclusiveMinimum: T, annotations?: Filter) => Filter<T>

Creates a greater-than-or-equal-to (>=) check for any ordered type from an Order.Order instance.

Signature

declare function makeIsGreaterThanOrEqualTo<T>(options: {
readonly annotate?: (exclusiveMinimum: T) => Filter;
readonly formatter?: Formatter<T, string>;
readonly order: Order<T>;
}): (minimum: T, annotations?: Filter) => Filter<T>

Creates a less-than (<) check for any ordered type from an Order.Order instance.

Signature

declare function makeIsLessThan<T>(options: {
readonly annotate?: (exclusiveMaximum: T) => Filter;
readonly formatter?: Formatter<T, string>;
readonly order: Order<T>;
}): (exclusiveMaximum: T, annotations?: Filter) => Filter<T>

Creates a less-than-or-equal-to (<=) check for any ordered type from an Order.Order instance.

Signature

declare function makeIsLessThanOrEqualTo<T>(options: {
readonly annotate?: (exclusiveMaximum: T) => Filter;
readonly formatter?: Formatter<T, string>;
readonly order: Order<T>;
}): (maximum: T, annotations?: Filter) => Filter<T>

Creates a divisibility check for any numeric type from a remainder function and a zero value.

Signature

declare function makeIsMultipleOf<T>(options: {
readonly annotate?: (divisor: T) => Filter;
readonly formatter?: Formatter<T, string>;
readonly remainder: (input: T, divisor: T) => T;
readonly zero: NoInfer<T>;
}): (divisor: T, annotations?: Filter) => Filter<T>