Function discriminator

  • a schema that accepts discriminated unions

    Type Parameters

    • const D extends string
    • const M extends Record<string, CompiledSchema<Record<string, unknown>, unknown>>

    Parameters

    • discriminator: D
    • mapping: M

    Returns CompiledSchema<{
        [K in keyof M]: M[K] extends CompiledSchema<infer P, unknown>
            ? {
                [Y in keyof (Record<D, K> & P)]: (P & Record<D, K>)[Y]
            }
            : never
    }[keyof M], {
        discriminator: D;
        mapping: {
            -readonly [K in keyof M]: M[K] extends CompiledSchema<unknown, infer S>
                ? S
                : never
        };
    }>

    Example

    const schema = discriminator("choice", {
    one: properties({ val: boolean() }),
    two: properties({ val: float64() }),
    })
    schema.guard({ choice: "one", val: true });
    schema.guard({ choice: "two", val: 2.0 });