Home > Software design >  Infer multiple generics in Typescript
Infer multiple generics in Typescript

Time:04-11

Here is an abstract example of what I would like to be able to do: Let's say I have a tool that provides me with types that have the following format:

type FunctionA<In, Out> = (input: In) => Out;

I also have another tool which is a method that has the following mirrored format:

const funcB = <Out, In>(input: In) => input as any as Out;

What I'd like to be able to do is, instead of using the underlying types, write a function that would infer those types from the first tool and call the second tool with those infered types. Ideally it would look something like this, though this code obviously isn't correct:

const funcC = <Func extends FunctionA<infer I, infer O>>(input: I) => funcB<O, I>(input);

So I would then be able to use it like so:

/** Outside Source */
type A = FunctionA<string, number>;
/** Outside Source */

funcC<A>('text');

It seemed like something that would be simple at first, but I can't seem to wrap my head around a way to do it.

CodePudding user response:

Thanks, @jcalz, that's exactly what I was trying to achieve. The solution is to create helper conditional types for the proxy function:

type In<F extends FunctionA<any, any>> = F extends FunctionA<infer I, any> ? I : never;
type Out<F extends FunctionA<any, any>> = F extends FunctionA<any, infer O> ? O : never;

const funcC = <F extends FunctionA<any, any>>(input: In<F>) => funcB<Out<F>, In<F>>(input);

Sorry for the abstraction, it is a situation I ran into several times in the past when trying to connect different tools, but never had the time to properly address. Sadly I couldn't remember a concrete example to properly use in the question without it seeming like something is missing.

  • Related