I am struggling with defining a main function myMainFunction()
that accepts a list of functions with different return types as parameters.
My goal is to have the return type of myMainFunction
be determined by the return types of the functions passed to it as parameters. However, I am facing difficulties in implementing this.
Below is my current approach, which does not seem to be working as expected:
const funcA = async (): string => "Hello";
const funcB = async (): {name: string, age: number} => ({ name: "Jane", age: 123 });
const myMainFunction = async <F extends () => ReturnType<F>>(...functions: F[]): Promise<ReturnType<F>[]> => {
const res = await Promise.all(functions.map((fn) => fn()));
return res;
};
// This does not provide the expected result, as values has a type of Promise<string>[]
// I am anticipating values to be of type Promise<[string, {first: string, age: number }]>
const values = await myMainFunction(funcA, funcB);
The issue with the above code is that the variable values
is of type Promise<string>[]
. It seems to only consider the return type of the first function in the parameters.
My expectation is for values
to have a type of
Promise<[string, {first: string, age: number }]>
, representing the return types of funcA()
and funcB()
.
How can I achieve the desired outcome?