Attempting to devise a strongly-typed function for mapping over a uniform array of functions that yield arbitrary values.
I've tinkered with both approaches, and while they do produce the expected types, I encounter issues with the return value:
const executeFunctions = <T extends (() => any)[]>(
functionsArray: [...T],
): {
[P in keyof T]: ReturnType<T[P]>
} => {
const result = [];
for (let i = 0; i < functionsArray.length; i += 1) {
result.push(functionsArray[i]());
}
return result;
}
// ^ Error: Type 'any[]' is not assignable to type '{ [P in keyof T]: ReturnType<T[P]>; }'.ts(2322)
const results = executeFunctions([
() => 'hello',
() => 123,
() => true,
]);
// const results: [string, number, boolean]
const executeFunctions = <T extends (() => unknown)[]>(
tasks: [...T],
): {
[P in keyof T]: ReturnType<T[P]>;
} => tasks.map(task => task());
// ^ Error: Type 'unknown[]' is not assignable to type '{ [P in keyof T]: ReturnType<T[P]>; }'.ts(2322)
const results = executeFunctions([
() => 'hello',
() => 123,
() => true,
]);
// const results: [string, number, boolean]
How can I accurately determine the return type?