Skip to content

union ​

The first matching schema from a list — an "or": a value can be a number or a string, 'auto' or a number, etc.

Signature ​

ts
function union<const T extends readonly Schema[]>(options: T, msg?: Message): Schema<Infer<T[number]>>

Parameters ​

ParameterTypeDescription
optionsSchema[]Schemas checked in order
msgMessageCustom message if no schema matches

Notes ​

  • Schemas are checked in order; the result of the first matching one is returned, with its transforms.
  • If none matches, there is a single union error without details for each schema. For objects with a tag field (type) use variant: it shows the errors of the specific variant.
  • An empty value gives required unless one of the schemas is optional.
  • The result type is a union of the schema types: union([number(), literal('auto')]) → number | 'auto'.

Error codes ​

CodeWhenDefault message
requiredThe value is emptyRequired
unionNo schema matchesDoes not match any allowed type

Examples ​

ID — a number or a slug ​

ts
const id = union([pipe(coerce.number(), integer()), pipe(string(), pattern(/^[a-z0-9-]+$/))]);

validate(id, '42').data;        // 42
validate(id, 'my-post').data;   // 'my-post'
validate(id, 'My Post').errors; // { '': 'Does not match any allowed type' }

"auto" or a number ​

ts
const width = union([literal('auto'), pipe(number(), min(0))]); // 'auto' | number

See also ​

  • variant — objects with a tag field, clear errors
  • oneOf — one of specific values