Skip to content

Serializable tagged unions with schema data

A schema data declaration defines a tagged union that is also a schema: one name gives you the union type, a validator, and an encoder and decoder for it. Use it for values that leave the process, such as messages, API responses and persisted state. For a union that stays in memory, use data. VIP-74 defines the form.

export schema Address {
  readonly city: string
}
 
export schema data Delivery {
  Waiting
  Sent { readonly tracking: string; note?: string; address: Address }
  Failed { code: number }
}
 
const sent = Delivery.cases.Sent.make({ tracking: "TRK-1", address: { city: "Oslo" } })
 
function describe(delivery: Delivery): string {
  return match (delivery) {
    when { _tag: "Waiting" }: "waiting";
    when { _tag: "Sent", let tracking, let address }: `sent ${tracking} to ${address.city}`;
    when { _tag: "Failed", let code }: `failed with ${code}`;
  }
}
 
effect function roundTrip() {
  const wire = try Schema.encodeEffect(Delivery)(sent)
  const text = try Effect.try(() => JSON.stringify(wire))
  const back = try Schema.decodeUnknownEffect(Delivery)(try Effect.try(() => JSON.parse(text)))
  return `${text} -> ${describe(back)}`
}
// Run in an effect function:
//   try Console.log(describe(sent))
//   try Console.log(try roundTrip())
sent TRK-1 to Oslo
{"_tag":"Sent","tracking":"TRK-1","address":{"city":"Oslo"}} -> sent TRK-1 to Oslo

Delivery is both a value and a type. The value is an Effect Schema.TaggedUnion, which is Effect's schema for a union of objects that a _tag field tells apart. The type is the union of the three variants, each with a literal _tag.

Declare a schema data union

export schema data Shape {
  Empty
  Circle { readonly radius: number }
  Rectangle { width: number; height?: number }
}
// Run in an effect function: try Console.log(Object.keys(Shape.cases).join(", "))
// Output: Empty, Circle, Rectangle

The following rules apply to the declaration:

  • Write schema, data and the name on one line. schema data { ... } without a name declares an ordinary schema named data.
  • A variant is a bare name (Empty) or a name with a field list in braces (Circle { radius: number }).
  • Separate variants and fields with ;, , or a line break.
  • A field's type follows the same mapping as a schema field: primitives, arrays, records, unions, other schemas, and schema constants such as Schema.NumberFromString.
  • A field is writable unless you mark it readonly. name?: Type makes the field optional.
  • export schema data Name exports the value and the type under one name.

Construct a variant

export schema data Job {
  Queued
  Running { attempt: number }
}
 
const queued: Job = { _tag: "Queued" }
const running = Job.cases.Running.make({ attempt: 1 })
 
effect function build() {
  running.attempt = 2
  const checked = try Job.cases.Running.makeEffect({ attempt: 3 })
  return [queued._tag, running.attempt, checked.attempt].join(" ")
}
// Run in an effect function: try Console.log(try build())
// Output: Queued 2 3

Job.cases holds one schema per variant. Job.cases.Running.make(fields) adds the _tag and returns the variant. makeEffect does the same and returns an Effect that fails when the fields are invalid. A variant is a plain object, so an object literal with the right _tag is also a Job.

Job.Running(...) does not exist. That constructor form belongs to data.

Match on the variants

// expect-error: EK4701
export schema data Outcome {
  Passed
  Failed { reason: string }
  Skipped
}
 
function label(outcome: Outcome): string {
  return match (outcome) {
    when { _tag: "Passed" }: "passed";
    when { _tag: "Failed", let reason }: `failed: ${reason}`;
  }
}

Match a variant with an object tag pattern, when { _tag: "Failed", let reason }:. The compiler checks that a match without default covers every variant. The sample omits Skipped, so the compiler reports EK4701. For the pattern forms, see Pattern matching with match and is.

The schema value also carries Effect's own helpers, shown in the next sample: guards, isAnyOf and match.

Encode and decode

export schema data Reading {
  Missing
  Value { amount: Schema.NumberFromString }
}
 
effect function decodeAll() {
  const decode = Schema.decodeUnknownEffect(Reading)
  const value = try decode({ _tag: "Value", amount: "41" })
  const wire = try Schema.encodeEffect(Reading)(value)
  const unknownTag = decode({ _tag: "Lost" }) catch (error) => error._tag
  const badField = decode({ _tag: "Value", amount: 41 }) catch (error) => error.message
  return [
    Reading.match(value, { Missing: () => 0, Value: (v) => v.amount + 1 }),
    wire._tag === "Value" ? typeof wire.amount : "none",
    Reading.guards.Value(value),
    Reading.isAnyOf(["Missing"])(value),
    unknownTag,
    badField,
  ].join("\n")
}
// Run in an effect function: try Console.log(try decodeAll())
42
string
true
false
SchemaError
Expected string
  at ["amount"]

Schema.decodeUnknownEffect(Reading) returns a function from an unknown value to an Effect. The Effect succeeds with a Reading or fails with a Schema.SchemaError. Schema.encodeEffect(Reading) goes the other way. Each field uses its own schema in both directions: amount is a number in the program and a string on the wire. An input with an unknown _tag, or with a field of the wrong type, fails to decode.

Comparison with data and schema

The following table compares the three declarations.

data Name { ... }schema data Name { ... }schema Name { ... }
ShapeTagged unionTagged unionOne object type
Compiles toData.TaggedEnum and Data.taggedEnumSchema.TaggedUnionSchema.Struct
ConstructName.Variant({ ... })Name.cases.Variant.make({ ... })An object literal
Encode and decodeNoYesYes
Field typesAny TypeScript typeTypes with a schema form (EK2109 otherwise)Types with a schema form (EK2109 otherwise)
FieldsAlways readonlyWritable unless readonlyWritable unless readonly
Type parametersUp to fourNone (EK1502)None (EK1502)

Generic unions

// expect-error: EK1502
export schema data Loadable<A> {
  Idle
  Loaded { value: A }
}

A schema data declaration takes no type parameters, because a schema is a runtime value and a type parameter has none. To build one union per payload schema, write a function that takes the payload schema and returns Schema.TaggedUnion:

Effect
import { Schema } from "effect"
 
export const Loadable = <A extends Schema.Top>(value: A) =>
  Schema.TaggedUnion({ Idle: {}, Loaded: { value } })
 
export const LoadableCount = Loadable(Schema.Number)
export type LoadableCount = typeof LoadableCount.Type

Compiled TypeScript

export schema data Shape { ... } from the declaration section compiles to this Effect TypeScript:

Effect
import { Schema } from "effect"
 
export const Shape = Schema.TaggedUnion({
  Empty: {},
  Circle: { radius: Schema.Number },
  Rectangle: {
    width: Schema.mutableKey(Schema.Number),
    height: Schema.mutableKey(Schema.optional(Schema.Number)),
  },
})
export type Shape = typeof Shape.Type

The declaration file holds the same pair: export declare const Shape: Schema.TaggedUnion<...> and export type Shape = typeof Shape.Type. A TypeScript module imports Shape and uses it as any other Effect schema. The compiler adds no runtime helper.

Rules and diagnostics

The following table lists the diagnostics that a schema data declaration reports.

CodeCondition
EK1502The declaration has type parameters.
EK1504Two fields of a variant have no separator between them.
EK1505A variant body holds a member that is not a field, such as a method.
EK1506The declaration is ambient: declare schema data Name { ... }.
EK1601A variant field is named _tag.
EK1603The declaration follows export default. Export the name with export { Name as default }.
EK1604The declaration has no variant body.
EK1605Two variants have no separator between them.
EK1606A variant lists its payload in parentheses, such as Circle(radius: number).
EK2109A field's type has no schema form, or names something that is not a schema.
EK4701A match without default misses a variant.