Skip to content

Schema Projections

Projections extract one side of a codec as a standalone schema that validates that representation without running conversions or requiring conversion services. Plain builders follow the call rules.

Projecting to the decoded type (toType)

const CountFromText = Schema.FiniteFromString.check(
  Schema.isInt(), Schema.isGreaterThanOrEqualTo(1)
)
const CountValue = Schema.toType(CountFromText)
 
effect function inspectCount(input: unknown) {
  return try Schema.decodeUnknownEffect(CountValue)(input)
}
// Accepts 4. Rejects "4", 0, and 1.5.
// Run in an effect function:
//   try Console.log(try inspectCount(4))
//   for (const value of ["4", 0, 1.5]) { try Effect.catch(inspectCount(value), (error) => Console.log(error._tag)) }
4
SchemaError
SchemaError
SchemaError

Schema.toType turns a codec's decoded side into both Type and Encoded, retaining decoded-side checks while dropping conversions and services. Use it to validate already-decoded data or avoid double-decoding elements inside a multi-stage pipeline.

Projecting to the encoded type (toEncoded)

const Name = Schema.String.check(Schema.isMinLength(3)).pipe(
  Schema.decodeTo(Schema.Trim)
)
const NameInput = Schema.toEncoded(Name)
 
effect function inspectWireName(input: unknown) {
  return try Schema.decodeUnknownEffect(NameInput)(input)
}
// " x " passes unchanged: it has length 3 before trimming.
// Run in an effect function:
//   {
//     const jsonValue = try inspectWireName(" x ")
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
" x "

Schema.toEncoded uses the original encoded type on both sides, validating wire input without transforming it.

Side-specific checks

const ParcelCount = Schema.String.check(Schema.isMinLength(2)).pipe(
  Schema.decodeTo(Schema.FiniteFromString),
  Schema.check(Schema.isGreaterThan(5))
)
const TextOnly = Schema.toEncoded(ParcelCount)
const NumberOnly = Schema.toType(ParcelCount)
 
effect function compareViews() {
  const text = try Schema.decodeUnknownEffect(TextOnly)("00") // "00"
  const count = try Schema.decodeUnknownEffect(NumberOnly)(8) // 8
  return { text, count }
}
// Run in an effect function:
//   {
//     const jsonValue = try compareViews()
//     try Console.log(try Effect.try(() => JSON.stringify(jsonValue)))
//   }
//   try Effect.catch(Schema.decodeUnknownEffect(ParcelCount)("00"), (error) => Console.log(error._tag))
{"text":"00","count":8}
SchemaError

Each projection keeps only its own side's checks: TextOnly enforces length >= 2 without checking > 5, and NumberOnly enforces > 5 without any string constraint. Passing a projection does not guarantee the full codec will succeed ("00" passes TextOnly but fails ParcelCount).


The matching Effect page: effect.website/docs/v4/schema/projections