Hyperlinkv0.8.0-beta.28

Schema

Schema.tagfunctioneffect/Schema.ts:5950
tag<Tag>

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.

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 }
Source effect/Schema.ts:595027 lines
export interface tag<Tag extends SchemaAST.LiteralValue> extends withConstructorDefault<Literal<Tag>> {}

/**
 * Combines a {@link Literal} schema with {@link 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.
 *
 * **Example** (Defining a discriminated union tag)
 *
 * ```ts
 * 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 }
 * ```
 *
 * @see {@link tagDefaultOmit} to also omit the tag during encoding
 * @see {@link TaggedStruct} for a shorthand that adds `_tag` automatically
 * @category constructors
 * @since 3.10.0
 */
export function tag<Tag extends SchemaAST.LiteralValue>(literal: Tag): tag<Tag> {
  return Literal(literal).pipe(withConstructorDefault(Effect.succeed(literal)))
}
Referenced by 29 symbols