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
| Parameter | Type | Description |
|---|---|---|
options | Schema[] | Schemas checked in order |
msg | Message | Custom 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
unionerror without details for each schema. For objects with a tag field (type) usevariant: it shows the errors of the specific variant. - An empty value gives
requiredunless one of the schemas isoptional. - The result type is a union of the schema types:
union([number(), literal('auto')])→number | 'auto'.
Error codes
| Code | When | Default message |
|---|---|---|
required | The value is empty | Required |
union | No schema matches | Does 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