Interface VariantSchema<Choices, In>

Schema for the Variant types, which is a special kind of union type where every choice is a struct with a single field denoting the choice.

The _ branch is a special case which can be used to represent all other choices that are not explicitly defined. Unlike other branches, the _ schema is passed the entire input instead of just the value of the field.

Example

const Shape = Variant({
circle: Schema.struct({ radius: Schema.integer() }),
rectangle: Schema.struct({ width: Schema.integer(), height: Schema.integer() })
})

Type Parameters

  • Choices extends Schema.VariantChoices = {}

    Mapping of branch names to corresponding schemas.

  • In extends unknown = unknown

    Input type for which schema can be read.

Hierarchy

Methods

  • Convenience function to create a new variant value. Unlike the .from it has input typed so that type checker can help you to ensure that you are providing all the required fields. If invalid input is provided, the function will throw an error.

    Type Parameters

    • Choice extends {
          [Key in never]?: undefined
      } & {
          [Key in string | number | symbol]: Choices[keyof Choices] extends Schema.Reader<T, unknown, Schema.Error>
              ? T
              : never
      }

    Parameters

    • input: Choice

    Returns Choice

  • Parameters

    • value: unknown

    Returns value is Schema.InferVariant<Choices>

  • Function can be used to match the input against the variant schema to return the matched branch name and corresponding value. It provides convenience over standard .read / .from methods by allowing user to switch over the branch name as opposed to having to do nested if else blocks.

    Type Parameters

    • Else = never

    Parameters

    • input: unknown

      Input to match against the variant schema.

    • Optional fallback: Else

      Fall back value to return if the input does not match any of the branches. If not provided, the function will throw an error if the input does not match any of the branches.

    Returns Schema.InferVariantMatch<Choices> | (Else extends never
        ? never
        : [null, Else])

    Example

    const [kind, shape] = Shape.match(input)
    switch (kind) {
    case "circle": return `Circle with radius ${shape.radius}`
    case "rectangle": return `Rectangle with width ${shape.width} and height ${shape.height}`
    }

Generated using TypeDoc