SchemaGetter.ts
SchemaGetter.ts overview
Section titled “SchemaGetter.ts overview”Builds one-way conversions used by schemas.
A Getter<T, E, R> receives an optional encoded value and returns an
optional decoded value. It can also report a schema issue or require Effect
services. Schema transformations use getters to describe one direction of a
conversion, for example decoding a field from input data. This module
includes basic getters, validation helpers, pure and effectful conversions,
and ready-made conversions for common string, number, binary, date, form, and
URL-related values.
Since v4.0.0
Exports Grouped by Category
Section titled “Exports Grouped by Category”- Base64 getters
- Coercions
- DateTime
- FormData
- Hex getters
- JSON getters
- Tree
- URI
- constructors
- models
- search params
- string
Base64 getters
Section titled “Base64 getters”decodeBase64
Section titled “decodeBase64”Decodes a Base64 string to a Uint8Array.
Details
- Fails with
SchemaIssue.InvalidValueif the input is not valid Base64.
Example (Decoding Base64 to bytes)
import { SchemaGetter } from "effect"
const decode = SchemaGetter.decodeBase64<string>()// Getter<Uint8Array, string>See
decodeBase64Stringto decode tostringinsteadencodeBase64for the inverse operation
Signature
declare const decodeBase64: <E extends string>() => Getter<Uint8Array, E>Since v4.0.0
decodeBase64String
Section titled “decodeBase64String”Decodes a Base64 string to a UTF-8 string.
Details
- Fails with
SchemaIssue.InvalidValueif the input is not valid Base64.
Example (Decoding Base64 to string)
import { SchemaGetter } from "effect"
const decode = SchemaGetter.decodeBase64String<string>()// Getter<string, string>See
decodeBase64to decode toUint8ArrayinsteadencodeBase64for the inverse operation
Signature
declare const decodeBase64String: <E extends string>() => Getter<string, E>Since v4.0.0
decodeBase64Url
Section titled “decodeBase64Url”Decodes a URL-safe Base64 string to a Uint8Array.
Details
- Fails with
SchemaIssue.InvalidValueif the input is not valid Base64Url.
Example (Decoding Base64Url to bytes)
import { SchemaGetter } from "effect"
const decode = SchemaGetter.decodeBase64Url<string>()// Getter<Uint8Array, string>See
decodeBase64UrlStringto decode tostringinsteadencodeBase64Urlfor the inverse operation
Signature
declare const decodeBase64Url: <E extends string>() => Getter<Uint8Array, E>Since v4.0.0
decodeBase64UrlString
Section titled “decodeBase64UrlString”Decodes a URL-safe Base64 string to a UTF-8 string.
Details
- Fails with
SchemaIssue.InvalidValueif the input is not valid Base64Url.
Example (Decoding Base64Url to string)
import { SchemaGetter } from "effect"
const decode = SchemaGetter.decodeBase64UrlString<string>()// Getter<string, string>See
decodeBase64Urlto decode toUint8ArrayinsteadencodeBase64Urlfor the inverse operation
Signature
declare const decodeBase64UrlString: <E extends string>() => Getter<string, E>Since v4.0.0
encodeBase64
Section titled “encodeBase64”Encodes a Uint8Array or string to a Base64 string.
Details
The getter is pure and never fails.
Example (Encoding to Base64)
import { SchemaGetter } from "effect"
const encode = SchemaGetter.encodeBase64<Uint8Array>()See
decodeBase64for the inverse operation toUint8ArraydecodeBase64Stringfor the inverse operation tostringencodeBase64Urlfor the URL-safe variant
Signature
declare const encodeBase64: <E extends Uint8Array | string>() => Getter<string, E>Since v4.0.0
encodeBase64Url
Section titled “encodeBase64Url”Encodes a Uint8Array or string to a URL-safe Base64 string.
Details
The getter is pure and never fails.
Example (Encoding to Base64Url)
import { SchemaGetter } from "effect"
const encode = SchemaGetter.encodeBase64Url<Uint8Array>()See
decodeBase64Urlfor the inverse operation toUint8ArraydecodeBase64UrlStringfor the inverse operation tostringencodeBase64for the standard Base64 variant
Signature
declare const encodeBase64Url: <E extends Uint8Array | string>() => Getter<string, E>Since v4.0.0
Coercions
Section titled “Coercions”BigInt
Section titled “BigInt”Coerces a value to bigint using the global BigInt() constructor.
When to use
Use when you need a schema getter to convert a present string, number, or
boolean value to bigint.
Details
- Delegates to
globalThis.BigInt. - Throws at runtime if the input cannot be converted (e.g. non-numeric string).
Example (Coercing to a bigint)
import { SchemaGetter } from "effect"
const toBigInt = SchemaGetter.BigInt<string>()// Getter<bigint, string>Signature
declare const BigInt: <E extends string | number | bigint | boolean>() => Getter<bigint, E>Since v4.0.0
Boolean
Section titled “Boolean”Coerces any value to a boolean using the global Boolean() constructor.
When to use
Use when you need a schema getter to coerce a present encoded value to a
boolean with Boolean().
Details
The getter is pure, never fails, and delegates to globalThis.Boolean.
Example (Coercing to a boolean)
import { SchemaGetter } from "effect"
const toBool = SchemaGetter.Boolean<string>()// Getter<boolean, string>Signature
declare const Boolean: <E>() => Getter<boolean, E>Since v4.0.0
Coerces a value to a Date using new Date(input).
When to use
Use when you need a schema getter to coerce a present string, number, or existing date object into a new date object.
Details
- Delegates to
new globalThis.Date(input). - Does not validate the result — may produce an invalid Date.
Example (Coercing to a Date)
import { SchemaGetter } from "effect"
const toDate = SchemaGetter.Date<string>()// Getter<Date, string>See
dateTimeUtcFromInputfor validated DateTime parsing
Signature
declare const Date: <E extends string | number | Date>() => Getter<Date, E>Since v4.0.0
Number
Section titled “Number”Coerces any value to a number using the global Number() constructor.
When to use
Use when you need a schema getter to coerce a present encoded value to a
number with Number().
Details
The getter is pure, never fails, and delegates to globalThis.Number. It may
produce NaN for non-numeric inputs.
Example (Coercing to a number)
import { SchemaGetter } from "effect"
const toNumber = SchemaGetter.Number<string>()// Getter<number, string>See
transformOrFailfor validated number parsing
Signature
declare const Number: <E>() => Getter<number, E>Since v4.0.0
String
Section titled “String”Coerces any value to a string using the global String() constructor.
When to use
Use when you need a schema getter to coerce a present encoded value to a
string with String().
Details
The getter is pure, never fails, and delegates to globalThis.String.
Example (Coercing to a string)
import { SchemaGetter } from "effect"
const toString = SchemaGetter.String<number>()// Getter<string, number>See
transformfor custom string conversions
Signature
declare const String: <E>() => Getter<string, E>Since v4.0.0
DateTime
Section titled “DateTime”dateTimeUtcFromInput
Section titled “dateTimeUtcFromInput”Parses a DateTime.Input value into a DateTime.Utc.
When to use
Use when you need a schema getter to decode a present encoded date/time value
to a DateTime.Utc.
Details
- Accepted input includes existing
DateTimevalues, partial date/time parts, instant objects, zoned instant objects, JavaScriptDateinstances, epoch milliseconds, and date strings. - Converts successfully parsed values to UTC.
- Fails with
SchemaIssue.InvalidValueif the input cannot be parsed as a validDateTime.
Example (Parsing DateTime)
import { SchemaGetter } from "effect"
const parseDate = SchemaGetter.dateTimeUtcFromInput<string>()// Getter<DateTime.Utc, string>See
Datefor a simpler coercion toDate(no validation)
Signature
declare const dateTimeUtcFromInput: <E extends DateTime.DateTime.Input>() => Getter<DateTime.Utc, E>Since v4.0.0
FormData
Section titled “FormData”decodeFormData
Section titled “decodeFormData”Decodes a FormData object into a nested tree structure using bracket-path notation.
When to use
Use when you need a schema getter to parse FormData from HTTP requests into
structured objects.
Details
The getter is pure and never fails. It interprets bracket-path keys such as
user[name] and items[0] to build nested objects or arrays, and each leaf
value is a string or Blob.
Example (Decoding FormData)
import { SchemaGetter } from "effect"
const decode = SchemaGetter.decodeFormData()// Getter<TreeObject<string | Blob>, FormData>See
encodeFormDatafor the inverse operationmakeTreeRecordfor the underlying bracket-path parserdecodeURLSearchParamsfor the URLSearchParams variant
Signature
declare const decodeFormData: () => Getter<Schema.TreeRecord<string | Blob>, FormData>Since v4.0.0
encodeFormData
Section titled “encodeFormData”Encodes a nested object into a FormData instance using bracket-path notation.
When to use
Use when you need a schema getter to serialize structured data to FormData
for HTTP requests.
Details
The getter is pure and never fails. It flattens nested objects or arrays into
bracket-path keys such as user[name] and items[0]. Non-object inputs
produce an empty FormData.
Example (Encoding to FormData)
import { SchemaGetter } from "effect"
const encode = SchemaGetter.encodeFormData()// Getter<FormData, unknown>See
decodeFormDatafor the inverse operationcollectBracketPathEntriesfor the underlying flattenerencodeURLSearchParamsfor the URLSearchParams variant
Signature
declare const encodeFormData: () => Getter<FormData, unknown>Since v4.0.0
Hex getters
Section titled “Hex getters”decodeHex
Section titled “decodeHex”Decodes a hexadecimal string to a Uint8Array.
Details
- Fails with
SchemaIssue.InvalidValueif the input is not valid hex.
Example (Decoding hex to bytes)
import { SchemaGetter } from "effect"
const decode = SchemaGetter.decodeHex<string>()// Getter<Uint8Array, string>See
decodeHexStringto decode tostringinsteadencodeHexfor the inverse operation
Signature
declare const decodeHex: <E extends string>() => Getter<Uint8Array, E>Since v4.0.0
decodeHexString
Section titled “decodeHexString”Decodes a hexadecimal string to a UTF-8 string.
Details
- Fails with
SchemaIssue.InvalidValueif the input is not valid hex.
Example (Decoding hex to string)
import { SchemaGetter } from "effect"
const decode = SchemaGetter.decodeHexString<string>()// Getter<string, string>See
decodeHexto decode toUint8ArrayinsteadencodeHexfor the inverse operation
Signature
declare const decodeHexString: <E extends string>() => Getter<string, E>Since v4.0.0
encodeHex
Section titled “encodeHex”Encodes a Uint8Array or string to a hexadecimal string.
Details
The getter is pure and never fails.
Example (Encoding to hex)
import { SchemaGetter } from "effect"
const encode = SchemaGetter.encodeHex<Uint8Array>()See
decodeHexfor the inverse operation toUint8ArraydecodeHexStringfor the inverse operation tostring
Signature
declare const encodeHex: <E extends Uint8Array | string>() => Getter<string, E>Since v4.0.0
JSON getters
Section titled “JSON getters”parseJson
Section titled “parseJson”Parses a JSON string into a value.
When to use
Use when you need a schema getter to parse a present encoded JSON string during decoding.
Details
- Skips
Noneinputs. - Without
reviver: returnsSchema.MutableJson(typed JSON). - With
reviver: returnsunknown(reviver may produce arbitrary values). - On parse failure, fails with
SchemaIssue.InvalidValuecontaining the error message.
Example (Parsing JSON)
import { SchemaGetter } from "effect"
const parse = SchemaGetter.parseJson<string>()// Getter<MutableJson, string>See
stringifyJsonfor the inverse operation
Signature
declare const parseJson: { <E extends string>(): Getter<Schema.MutableJson, E> <E extends string>(options: ParseJsonOptions): Getter<unknown, E>}Since v4.0.0
stringifyJson
Section titled “stringifyJson”Stringifies a present value using JSON.stringify.
When to use
Use when you need a schema getter to serialize a present decoded value to JSON text during encoding.
Details
- Skips
Noneinputs. - On thrown stringify failures, such as circular references, fails with
SchemaIssue.InvalidValue. - Supports optional
replacerandspaceoptions, matchingJSON.stringify. - If
JSON.stringifyreturnsundefined, such as forundefined, functions, symbols, or a replacer that removes the root value, thatundefinedresult is returned rather than converted into anIssue.
Example (Stringifying JSON)
import { SchemaGetter } from "effect"
const stringify = SchemaGetter.stringifyJson()// Getter<string, unknown>See
parseJsonfor the inverse operation
Signature
declare const stringifyJson: (options?: StringifyJsonOptions) => Getter<string, unknown>Since v4.0.0
collectBracketPathEntries
Section titled “collectBracketPathEntries”Flattens a nested object into bracket-path entries, filtering leaf values by a type guard.
When to use
Use when you need a schema getter to serialize structured objects to flat key-value entries.
- Building custom
FormDataorURLSearchParamsencoders.
Details
- This is the inverse of
makeTreeRecord. - Takes a nested object and produces flat
[bracketPath, value]pairs suitable forFormDataorURLSearchParams. - Returns a curried function: first call provides the leaf type guard, second call provides the object.
- Recursively traverses objects and arrays.
- If all elements of an array are leaves, encodes them as multiple entries with the same key
(e.g.
tags=a&tags=b). Otherwise uses indexed bracket paths (e.g.items[0],items[1]). - Non-leaf values that aren’t objects or arrays are silently skipped.
Example (Flattening an object to bracket paths)
import { Predicate, SchemaGetter } from "effect"
const collectStrings = SchemaGetter.collectBracketPathEntries(Predicate.isString)const entries = collectStrings({ user: { name: "Alice", tags: ["admin", "editor"] } })// [["user[name]", "Alice"], ["user[tags]", "admin"], ["user[tags]", "editor"]]See
makeTreeRecordfor the inverse operation (flat entries to tree)encodeFormDatafor a higher-level FormData encoderencodeURLSearchParamsfor a higher-level URLSearchParams encoder
Signature
declare const collectBracketPathEntries: <A>( isLeaf: (value: unknown) => value is A) => (input: object) => Array<[bracketPath: string, value: A]>Since v4.0.0
makeTreeRecord
Section titled “makeTreeRecord”Builds a nested tree object from a list of bracket-path entries.
When to use
Use when you need a schema getter to parse FormData or URLSearchParams entries into structured objects.
- You have flat key-value pairs with bracket-path keys that need nesting.
Details
- A bracket path is a string like
"user[address][city]"that describes nested object/array structure. - Interprets bracket paths and constructs the corresponding nested object.
- Builds and returns a nested object from the input entries.
- Supported syntax:
"foo"→ object key"foo""foo[bar]"→ nested{ foo: { bar: ... } }"foo[0]"→ array index{ foo: [value] }"foo[]"→ append to arrayfoo""→ real empty key
- Duplicate keys for the same path are merged into arrays.
Example (Building a tree from bracket paths)
import { SchemaGetter } from "effect"
const tree = SchemaGetter.makeTreeRecord([ ["user[name]", "Alice"], ["user[tags][]", "admin"], ["user[tags][]", "editor"]])// { user: { name: "Alice", tags: ["admin", "editor"] } }See
collectBracketPathEntriesfor the inverse operation (tree to flat entries)decodeFormDatafor a higher-level FormData decoderdecodeURLSearchParamsfor a higher-level URLSearchParams decoder
Signature
declare const makeTreeRecord: <A>( bracketPathEntries: ReadonlyArray<readonly [bracketPath: string, value: A]>) => Schema.TreeRecord<A>Since v4.0.0
decodeUriComponent
Section titled “decodeUriComponent”Decodes a URI component encoded string using decodeURIComponent.
Details
- Fails with
SchemaIssue.InvalidValueif the input contains malformed percent-encoding sequences.
Example (Decoding a URI component)
import { SchemaGetter } from "effect"
const decode = SchemaGetter.decodeUriComponent<string>()// Getter<string, string>See
encodeUriComponentfor the inverse operation
Signature
declare const decodeUriComponent: <E extends string>() => Getter<string, E>Since v4.0.0
encodeUriComponent
Section titled “encodeUriComponent”Encodes a present string using encodeURIComponent.
Details
- Skips
Noneinputs. - May throw a
URIErrorfor malformed surrogate pairs; this exception is not converted into anIssue.
Example (Encoding a URI component)
import { SchemaGetter } from "effect"
const encode = SchemaGetter.encodeUriComponent<string>()See
decodeUriComponentfor the inverse operation
Signature
declare const encodeUriComponent: <E extends string>() => Getter<string, E>Since v4.0.0
constructors
Section titled “constructors”checkEffect
Section titled “checkEffect”Creates a getter that validates a value using an effectful check function.
When to use
Use when you need a schema getter to validate a decoded value (e.g. check a constraint or call an external service).
- The validation may be asynchronous or require Effect services.
Details
- Only runs when input is
Some—Nonepasses through. - The check function returns a validation result:
undefinedortrue— value is valid, passes through.falseor astring— value is invalid, fails with anIssue.- An
Issueobject — fails with that issue directly. { path, issue }— fails with a nested path issue (issuemay be a message string or a fullSchemaIssue.Issue).
- Does not transform the value — input and output types are the same.
Example (Validating effectfully)
import { Effect, SchemaGetter } from "effect"
const nonNegative = SchemaGetter.checkEffect<number>((n) => Effect.succeed(n >= 0 ? undefined : "must be non-negative"))See
transformwhen you need to change the value, not just validatefailfor unconditional failure
Signature
declare const checkEffect: <T, R = never>( f: (input: T, options: SchemaAST.ParseOptions) => Effect.Effect<undefined | boolean | Schema.FilterIssue, never, R>) => Getter<T, T, R>Since v4.0.0
Creates a getter that always fails with the given issue.
When to use
Use when you need a schema getter that unconditionally rejects input.
- Building custom validation getters that produce specific error types.
Details
- Always fails with the
Issuereturned byf. - The failure function receives the original
Option<E>input for error context.
Example (Defining an always-failing getter)
import { Option, SchemaGetter, SchemaIssue } from "effect"
const rejectAll = SchemaGetter.fail<string, string>( (oe) => new SchemaIssue.InvalidValue(oe, { message: "not allowed" }))See
forbiddenfor a convenience helper forForbiddenissuescheckEffectto fail conditionally based on input value
Signature
declare const fail: <T, E>(f: (oe: Option.Option<E>) => SchemaIssue.Issue) => Getter<T, E>Since v4.0.0
forbidden
Section titled “forbidden”Creates a getter that always fails with a Forbidden issue.
When to use
Use when you need a schema getter to disallow a field or direction (encode/decode) entirely.
- You want a clear “forbidden” error message in schema validation output.
Details
- Always fails with
SchemaIssue.Forbidden. - The message function receives the
Option<E>input for context.
Example (Forbidding a decode direction)
import { SchemaGetter } from "effect"
const noEncode = SchemaGetter.forbidden<string, number>(() => "encoding is not supported")See
failto fail with a custom issue type
Signature
declare const forbidden: <T, E>(message: (oe: Option.Option<E>) => string) => Getter<T, E>Since v4.0.0
Creates a getter that always returns None, effectively omitting the value from output.
When to use
Use when you need a schema getter to exclude a field during decoding or encoding.
Details
- Always returns
Option.Noneregardless of input. - Never fails.
Example (Omitting a field during encoding)
import { SchemaGetter } from "effect"
const omitField = SchemaGetter.omit<string>()See
transformOptionalwhen you want conditional omissionforbiddenwhen you want to fail instead of silently omit
Signature
declare const omit: <T>() => Getter<never, T>Since v4.0.0
onNone
Section titled “onNone”Creates a getter that handles the case when the input is absent (Option.None).
When to use
Use when you need a schema getter to provide a fallback or computed value for missing struct keys.
- Building custom “default value” logic more complex than
withDefault.
Details
- When input is
None, callsfto produce the result. - When input is
Some, passes it through unchanged. freceives the parse options and may returnNoneto keep the value absent.
Example (Providing a default timestamp for a missing field)
import { Effect, Option, SchemaGetter } from "effect"
const withTimestamp = SchemaGetter.onNone<number>(() => Effect.succeed(Option.some(Date.now())))See
requiredwhen absent input should failwithDefaultfor a simpler default value for undefined inputsonSometo handle only present values
Signature
declare const onNone: <T, E extends T = T, R = never>( f: (options: SchemaAST.ParseOptions) => Effect.Effect<Option.Option<T>, SchemaIssue.Issue, R>) => Getter<T, E, R>Since v4.0.0
onSome
Section titled “onSome”Creates a getter that handles present values (Option.Some), passing None through.
When to use
Use when you need a schema getter to transform or validate only when a field value is present.
- Missing keys should remain absent in the output.
Details
- When input is
None, returnsNone(no-op). - When input is
Some(e), callsf(e, options)to produce the result. fmay returnNoneto omit the value, or fail with anIssue.
Example (Transforming only present values)
import { Effect, Option, SchemaGetter } from "effect"
const parseIfPresent = SchemaGetter.onSome<number, string>((s) => Effect.succeed(Option.some(Number(s))))See
onNoneto handle only absent valuestransformfor a simpler pure transformation of present valuestransformOrFailfor fallible transformation of present values
Signature
declare const onSome: <T, E, R = never>( f: (e: E, options: SchemaAST.ParseOptions) => Effect.Effect<Option.Option<T>, SchemaIssue.Issue, R>) => Getter<T, E, R>Since v4.0.0
passthrough
Section titled “passthrough”Returns the identity getter — passes the value through unchanged.
When to use
Use when you need a schema getter for one side of a decodeTo pair, either
encode or decode, to pass values through unchanged.
Details
- Pure, no allocation (singleton instance).
- Optimized away during
.compose()— composing with a passthrough is free. - The default overload requires
T === E. Pass{ strict: false }to opt out of the type constraint.
Example (Passing through identity transformations)
import { Schema, SchemaGetter } from "effect"
// No transformation needed — types already matchconst StringToString = Schema.String.pipe( Schema.decodeTo(Schema.String, { decode: SchemaGetter.passthrough(), encode: SchemaGetter.passthrough() }))See
passthroughSupertypewhenT extends EpassthroughSubtypewhenE extends Ttransformwhen you need to change the value
Signature
declare const passthrough: { <T, E>(options: { readonly strict: false }): Getter<T, E>; <T>(): Getter<T, T> }Since v4.0.0
passthroughSubtype
Section titled “passthroughSubtype”Returns the identity getter, typed for when the encoded type E is a subtype of T.
When to use
Use when you need a schema getter that passes values through without
{ strict: false } for an encoded type that narrows the decoded type.
Details
- Same singleton as
passthrough— no allocation, optimized in composition.
Example (Passing through subtypes)
import { SchemaGetter } from "effect"
// "hello" extends string, so E extends Tconst g = SchemaGetter.passthroughSubtype<string, "hello">()See
passthroughwhen types are identicalpassthroughSupertypewhenT extends E
Signature
declare const passthroughSubtype: <T, E extends T>() => Getter<T, E>Since v4.0.0
passthroughSupertype
Section titled “passthroughSupertype”Returns the identity getter typed for the relationship T extends E.
When to use
Use when you need a schema getter that passes values through when the decoded/output type is narrower than the encoded/input type.
Details
- Same singleton as
passthrough— no allocation, optimized in composition.
Example (Passing through supertypes)
import { SchemaGetter } from "effect"
// string extends string, so this is validconst g = SchemaGetter.passthroughSupertype<string, string>()See
passthroughwhen types are identicalpassthroughSubtypewhenE extends T
Signature
declare const passthroughSupertype: <T extends E, E>() => Getter<T, E>Since v4.0.0
required
Section titled “required”Creates a getter that fails with MissingKey if the input is absent (Option.None).
When to use
Use when you need a schema getter to require a struct field in the encoded input and report a missing key error when it is absent.
Details
- When input is
None, fails withSchemaIssue.MissingKey. - When input is
Some, passes it through unchanged. - Optional
annotationscustomize the error message for the missing key.
Example (Defining a required struct field)
import { SchemaGetter } from "effect"
const mustExist = SchemaGetter.required<string>()See
onNoneto provide a fallback instead of failingwithDefaultto substitute a default for undefined values
Signature
declare const required: <T, E extends T = T>(annotations?: Schema.Annotations.Key<T>) => Getter<T, E>Since v4.0.0
succeed
Section titled “succeed”Creates a getter that always produces the given constant value, ignoring the input.
When to use
Use when you need a schema getter that always decodes a field to a fixed value.
Details
The getter is pure and always returns Option.some(t) regardless of whether
the input is Some or None.
Example (Returning a constant getter)
import { SchemaGetter } from "effect"
const alwaysZero = SchemaGetter.succeed(0)// alwaysZero: Getter<0, unknown> — always produces 0See
transformwhen you need to use the input valuepassthroughwhen you want to keep the input as-is
Signature
declare const succeed: <const T, E>(t: T) => Getter<T, E>Since v4.0.0
transform
Section titled “transform”Creates a getter that applies a pure function to present values.
When to use
Use when you need a schema getter for a pure, infallible transformation between types.
- Building encode/decode pairs for
Schema.decodeTo.
Details
- This is the most commonly used constructor.
- Transforms
Some(e)toSome(f(e))and leavesNoneunchanged. - Skips
Noneinputs — only called when a value is present. - Never fails.
Example (Transforming strings to numbers)
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)) }))See
transformOrFailwhen the transformation can failtransformOptionalwhen you need to handleNoneinputspassthroughwhen no transformation is needed
Signature
declare const transform: <T, E>(f: (e: E) => T) => Getter<T, E>Since v4.0.0
transformOptional
Section titled “transformOptional”Creates a getter that transforms the full Option — both present and absent values.
When to use
Use when you need a schema getter to handle both Some and None cases.
Details
The getter is pure and never fails. It receives the full Option<E> and
must return Option<T>, so it can turn a present value into absent or an
absent value into present.
Example (Filtering out empty strings)
import { Option, SchemaGetter } from "effect"
const skipEmpty = SchemaGetter.transformOptional<string, string>((o) => Option.filter(o, (s) => s.length > 0))See
transformwhen you only need to transform present valuesomitwhen you always wantNone
Signature
declare const transformOptional: <T, E>(f: (oe: Option.Option<E>) => Option.Option<T>) => Getter<T, E>Since v4.0.0
transformOrFail
Section titled “transformOrFail”Creates a getter that applies a fallible, effectful transformation to present values.
When to use
Use when you need a schema getter for a transformation that may fail, require Effect services, or run asynchronously.
Details
- Skips
Noneinputs — only called when a value is present. - On success, wraps the result in
Some. - On failure, propagates the
Issue.
Example (Parsing with failure)
import { Effect, Option, SchemaGetter, SchemaIssue } from "effect"
const safeParseInt = SchemaGetter.transformOrFail<number, string>((s) => { const n = parseInt(s, 10) return isNaN(n) ? Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: "not an integer" })) : Effect.succeed(n)})See
transformwhen transformation cannot failonSomewhen you need fullOptioncontrol over the output
Signature
declare const transformOrFail: <T, E, R = never>( f: (e: E, options: SchemaAST.ParseOptions) => Effect.Effect<T, SchemaIssue.Issue, R>) => Getter<T, E, R>Since v4.0.0
withDefault
Section titled “withDefault”Creates a getter that replaces undefined values with a default.
When to use
Use when you need a schema getter to provide a fallback for a field that may
be undefined in the encoded input.
Details
- If the input is
Some(undefined)orNone, producesSome(T). - If the input is
Some(value)where value is notundefined, passes it through. defaultValueis anEffectthat will be executed each time a default is needed.
Example (Providing a default value for an optional field)
import { Effect, SchemaGetter } from "effect"
const withZero = SchemaGetter.withDefault(Effect.succeed(0))// Getter<number, number | undefined>See
onNoneto handle only absent keys (notundefinedvalues)requiredwhen absent input should fail instead of using a default
Signature
declare const withDefault: <T, R = never>( defaultValue: Effect.Effect<T, SchemaIssue.Issue, R>) => Getter<T, T | undefined, R>Since v4.0.0
models
Section titled “models”Getter (class)
Section titled “Getter (class)”Represents a composable transformation from an encoded type E to a decoded type T.
When to use
Use when you need a schema getter to build and compose custom transformations
for Schema.decodeTo or Schema.decode.
Details
A getter wraps a function Option<E> -> Effect<Option<T>, Issue, R>. It
receives Option.None when the encoded key is absent, such as a missing
struct field, and returns Option.None to omit the value from the decoded
output. It fails with Issue on invalid input and may require Effect
services via R. .map(f) applies f to the decoded value inside Some
while leaving None unchanged. .compose(other) chains two getters by
feeding the output of this into other; passthrough getters on either side
are optimized away.
Example (Creating and composing getters)
import { SchemaGetter } from "effect"
const parseNumber = SchemaGetter.transform<number, string>((s) => Number(s))const double = SchemaGetter.transform<number, number>((n) => n * 2)const composed = parseNumber.compose(double)// composed: Getter<number, string> — parses then doublesSee
transformto create a getter from a pure functionpassthroughfor the identity gettertransformOrFailfor fallible transformation
Signature
declare class Getter<T, E, R> { constructor( run: ( input: Option.Option<E>, options: SchemaAST.ParseOptions ) => Effect.Effect<Option.Option<T>, SchemaIssue.Issue, R> )}Since v4.0.0
map (method)
Section titled “map (method)”Signature
declare const map: <T2>(f: (t: T) => T2) => Getter<T2, E, R>compose (method)
Section titled “compose (method)”Signature
declare const compose: <T2, R2>(other: Getter<T2, T, R2>) => Getter<T2, E, R | R2>run (property)
Section titled “run (property)”Signature
readonly run: (input: Option.Option<E>, options: SchemaAST.ParseOptions) => Effect.Effect<Option.Option<T>, SchemaIssue.Issue, R>search params
Section titled “search params”decodeURLSearchParams
Section titled “decodeURLSearchParams”Decodes a URLSearchParams object into a nested tree structure using bracket-path notation.
When to use
Use when you need a schema getter to parse query parameters from URLs into structured objects.
Details
The getter is pure and never fails. It interprets bracket-path keys such as
user[name] and items[0] to build nested objects or arrays, and each leaf
value is a string.
Example (Decoding URLSearchParams)
import { SchemaGetter } from "effect"
const decode = SchemaGetter.decodeURLSearchParams()// Getter<TreeObject<string>, URLSearchParams>See
encodeURLSearchParamsfor the inverse operationmakeTreeRecordfor the underlying bracket-path parserdecodeFormDatafor the FormData variant
Signature
declare const decodeURLSearchParams: () => Getter<Schema.TreeRecord<string>, URLSearchParams>Since v4.0.0
encodeURLSearchParams
Section titled “encodeURLSearchParams”Encodes a nested object into a URLSearchParams instance using bracket-path notation.
When to use
Use when you need a schema getter to serialize structured data to query parameters for URLs.
Details
The getter is pure and never fails. It flattens nested objects or arrays into
bracket-path keys. Non-object inputs produce an empty URLSearchParams.
Example (Encoding to URLSearchParams)
import { SchemaGetter } from "effect"
const encode = SchemaGetter.encodeURLSearchParams()// Getter<URLSearchParams, unknown>See
decodeURLSearchParamsfor the inverse operationcollectBracketPathEntriesfor the underlying flattenerencodeFormDatafor the FormData variant
Signature
declare const encodeURLSearchParams: () => Getter<URLSearchParams, unknown>Since v4.0.0
string
Section titled “string”camelToSnake
Section titled “camelToSnake”Converts a camelCase string to snake_case.
Details
- Pure, delegates to
String.camelToSnake.
Example (Converting camel case to snake case)
import { SchemaGetter } from "effect"
const toSnake = SchemaGetter.camelToSnake<string>()See
snakeToCamelfor the inverse operation
Signature
declare const camelToSnake: <E extends string>() => Getter<string, E>Since v4.0.0
capitalize
Section titled “capitalize”Capitalizes the first character of a string.
Details
- Pure, delegates to
String.capitalize.
Example (Capitalizing a string)
import { SchemaGetter } from "effect"
const cap = SchemaGetter.capitalize<string>()Signature
declare const capitalize: <E extends string>() => Getter<string, E>Since v4.0.0
joinKeyValue
Section titled “joinKeyValue”Joins a record of key-value pairs into a delimited string.
When to use
Use when you need a schema getter to serialize a present decoded record as a delimited key-value string.
Details
The getter is pure and never fails. It joins entries with separator
(default ,) and joins each key and value with keyValueSeparator (default
=).
Example (Joining key-value records)
import { SchemaGetter } from "effect"
const join = SchemaGetter.joinKeyValue()// { a: "1", b: "2" } -> "a=1,b=2"See
splitKeyValuefor the inverse operation
Signature
declare const joinKeyValue: <E extends Record<PropertyKey, string>>(options?: { readonly separator?: string | undefined readonly keyValueSeparator?: string | undefined}) => Getter<string, E>Since v4.0.0
snakeToCamel
Section titled “snakeToCamel”Converts a snake_case string to camelCase.
Details
- Pure, delegates to
String.snakeToCamel.
Example (Converting snake case to camel case)
import { SchemaGetter } from "effect"
const toCamel = SchemaGetter.snakeToCamel<string>()See
camelToSnakefor the inverse operation
Signature
declare const snakeToCamel: <E extends string>() => Getter<string, E>Since v4.0.0
Splits a string into an array of strings by a separator.
When to use
Use when you need a schema getter to split a present encoded string containing a delimited list, such as CSV values.
Details
The getter is pure and never fails. It splits by separator (default ,).
An empty string produces an empty array, not [""].
Example (Splitting a comma-separated string)
import { SchemaGetter } from "effect"
const splitComma = SchemaGetter.split<string>()// "a,b,c" -> ["a", "b", "c"]// "" -> []See
splitKeyValuewhen values are key-value pairs
Signature
declare const split: <E extends string>(options?: { readonly separator?: string | undefined}) => Getter<ReadonlyArray<string>, E>Since v4.0.0
splitKeyValue
Section titled “splitKeyValue”Parses a string into a record of key-value pairs.
When to use
Use when you need a schema getter to parse a present encoded string that
contains delimited key-value pairs (e.g. "a=1,b=2").
Details
The getter is pure and never fails. It splits the string by separator
(default ,) and then each pair by keyValueSeparator (default =). Pairs
missing a key or value are silently skipped.
Example (Parsing a key-value string)
import { SchemaGetter } from "effect"
const parse = SchemaGetter.splitKeyValue<string>()// "a=1,b=2" -> { a: "1", b: "2" }See
joinKeyValuefor the inverse operationsplitto split into an array of strings
Signature
declare const splitKeyValue: <E extends string>(options?: { readonly separator?: string | undefined readonly keyValueSeparator?: string | undefined}) => Getter<Record<string, string>, E>Since v4.0.0
toLowerCase
Section titled “toLowerCase”Converts a string to lowercase.
Details
- Pure, delegates to
String.toLowerCase.
Example (Converting to lowercase)
import { SchemaGetter } from "effect"
const lower = SchemaGetter.toLowerCase<string>()See
toUpperCasefor the inverse operation
Signature
declare const toLowerCase: <E extends string>() => Getter<string, E>Since v4.0.0
toUpperCase
Section titled “toUpperCase”Converts a string to uppercase.
Details
- Pure, delegates to
String.toUpperCase.
Example (Converting to uppercase)
import { SchemaGetter } from "effect"
const upper = SchemaGetter.toUpperCase<string>()See
toLowerCasefor the inverse operation
Signature
declare const toUpperCase: <E extends string>() => Getter<string, E>Since v4.0.0
Strips whitespace from both ends of a string.
Details
- Pure, delegates to
String.trim.
Example (Trimming whitespace)
import { SchemaGetter } from "effect"
const trimmed = SchemaGetter.trim<string>()Signature
declare const trim: <E extends string>() => Getter<string, E>Since v4.0.0
uncapitalize
Section titled “uncapitalize”Uncapitalizes the first character of a string.
Details
- Pure, delegates to
String.uncapitalize.
Example (Uncapitalizing a string)
import { SchemaGetter } from "effect"
const uncap = SchemaGetter.uncapitalize<string>()Signature
declare const uncapitalize: <E extends string>() => Getter<string, E>Since v4.0.0