union
列表中第一个匹配的 Schema —— 即“或”:值可以是数字或字符串、'auto' 或数字等。
签名
ts
function union<const T extends readonly Schema[]>(options: T, msg?: Message): Schema<Infer<T[number]>>参数
| 参数 | 类型 | 说明 |
|---|---|---|
options | Schema[] | 按顺序检查的 Schema |
msg | Message | 没有任何 Schema 匹配时的自定义信息 |
注意事项
- 按顺序检查 Schema,返回第一个匹配的结果(包括它的转换)。
- 如果都不匹配,只产生一个
union错误,不包含每个 Schema 的详细信息。对于带有标识字段(type)的对象,请使用variant:它会显示具体变体的错误。 - 空值会产生
required,除非其中有optional。 - 结果类型是各 Schema 类型的联合:
union([number(), literal('auto')])→number | 'auto'。
错误代码
| 代码 | 触发条件 | 默认信息 |
|---|---|---|
required | 值为空 | Required |
union | 没有任何 Schema 匹配 | Does not match any allowed type |
示例
ID —— 数字或 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” 或数字
ts
const width = union([literal('auto'), pipe(number(), min(0))]); // 'auto' | number