Variant<U>: {
    [Key in keyof U]: {
        [K in Exclude<keyof U, Key>]?: never
    } & {
        [K in Key]: U[Key]
    }
}[keyof U]

Utility type for defining a keyed union type as in IPLD Schema. In practice this just works around typescript limitation that requires discriminant field on all variants.

type Result<T, X> =
| { ok: T }
| { error: X }

const demo = (result: Result<string, Error>) => {
if (result.ok) {
// ^^^^^^^^^ Property 'ok' does not exist on type '{ error: Error; }`
}
}

Using Variant type we can define same union type that works as expected:

type Result<T, X> = Variant<{
ok: T
error: X
}>

const demo = (result: Result<string, Error>) => {
if (result.ok) {
result.ok.toUpperCase()
}
}

Type Parameters

  • U extends Record<string, unknown>

Generated using TypeDoc