variant
多个对象变体,按标识字段(例如 type)选择变体。与 union 不同,它会显示所选变体的具体错误。
签名
ts
function variant<K extends string, const T extends readonly ObjectSchema[]>(key: K, options: T, msg?: Message): Schema<Infer<T[number]>>参数
| 参数 | 类型 | 说明 |
|---|---|---|
key | string | 标识字段的名称 |
options | ObjectSchema[] | object Schema。每个都必须包含 key 字段 —— 通常是 literal |
msg | Message | 值为空、不是对象或变体未知时的自定义信息 |
注意事项
- 按顺序用每个变体中
key字段的 Schema 检查标识,然后用匹配的变体校验整个对象。 - 标识可以是
literal、oneOf或enumOf—— 它们的值会出现在错误信息中。 - 未知变体的错误关联到标识字段:
errors.type。 - 结果类型是可辨识联合:在
if (data.type === 'card')之后,TypeScript 知道该变体的字段。
错误代码
| 代码 | 触发条件 | 默认信息 |
|---|---|---|
required | 值或标识为空 | Required |
object | 不是对象 | Must be an object |
variant | 标识值未知 | Unknown type, expected one of: {options} |
示例
支付方式
ts
const Payment = variant('type', [
object({ type: literal('card'), number: pipe(string(), length(16)) }),
object({ type: literal('invoice'), inn: pipe(string(), length(10)) }),
]);
validate(Payment, { type: 'card' }).errors; // { number: 'Required' }
validate(Payment, { type: 'cash' }).errors; // { type: 'Unknown type, expected one of: card, invoice' }
const payment = parse(Payment, body);
if (payment.type === 'card') payment.number; // string