Skip to content

variant ​

多个对象变体,按标识字段(例如 type)选择变体。与 union 不同,它会显示所选变体的具体错误。

签名 ​

ts
function variant<K extends string, const T extends readonly ObjectSchema[]>(key: K, options: T, msg?: Message): Schema<Infer<T[number]>>

参数 ​

参数类型说明
keystring标识字段的名称
optionsObjectSchema[]object Schema。每个都必须包含 key 字段 —— 通常是 literal
msgMessage值为空、不是对象或变体未知时的自定义信息

注意事项 ​

  • 按顺序用每个变体中 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

另请参阅 ​