variant
variant<T extends [ObjectSchema<any, any>, ...ObjectSchema<any, any>[]]>(
discriminant: keyof T[number]["props"],
schemas: T,
): UnionSchema<TypeOf<T[number]>, InputOf<T[number]>>
Type Parameters
- T extends [ObjectSchema<any, any>, ...ObjectSchema<any, any>[]]
Returns UnionSchema<TypeOf<T[number]>, InputOf<T[number]>>
Example
import * as x from 'unhoax'
const a = x.object({ type: x.literal('a'), a: x.string }),
const b = x.object({ type: x.literal('b'), b: x.number }),
const schema = x.variant('type', [a, b])
// Schema<{ type: 'a', a: string } | { type: 'b', b: number }>
const result = schema.parse({ type: 'a', a: 'Hello' })
// { success: true, value: { type: 'a', a: 'Hello' } }
If you need to use a simple union, checkout union