How to deduce the type of an object from the generic parameters held by the provided function?

30 views Asked by At
type AntiZodInfer<T> = T extends z.infer<
    infer InferZodType extends ZodType<any>
>
    ? InferZodType
    : never;

type SelectFn<Prams extends Record<string, any>> = <
    PramName extends keyof Prams
>(
    pramName: PramName,
    select: AntiZodInfer<Prams[PramName]>
) => SelectZodPattern<AntiZodInfer<Prams[PramName]>>;

class ToMatch<I, O> {
    is<Prams extends Record<string, any>, Pattern extends AntiZodInfer<I>>(
        pattern: (select: SelectFn<Prams>) => Pattern,
        ...rest:
            | [(prams: Prams) => boolean, (prams: Prams) => O]
            | [(prams: Prams) => O]
    ): ToMatch<I, O>;
}

I tried creating a class like this and tried to come up with a better Prams Record type through generic derivation of SelectFn. I used this class like this.

when({ a: 123 }).is(
    ($) => z.object({ a: $("num", z.number()) }),
    ({ num }) => num
);

The when is the constructor of the ToMatch class. When I looked at the type of Prams, I found that it was still Record<string, any>.

I would like Prams to be deduced into a more specific type { num: number }, is there a way I can achieve this?

0

There are 0 answers