I am currently working on a function that takes another function and its arguments as parameters, then runs the function with the provided arguments and returns the result while maintaining the data types.
If the function being provided has a fixed return type, everything works smoothly. However, when the return type of the function is dependent on the parameters, I encounter difficulties in preserving the return type.
Below is my unsuccessful attempt which illustrates what I am aiming to achieve:
function f<A>(args: A) {
return args
}
// Directly calling the function yields the expected output:
const result = f('test') // OK: type of result is 'test'
// I tried to explicitly define the return type but it was not successful
type ReturnTypeWithArgs<
F extends (args: any) => any,
A extends Parameters<F>[0],
> = F extends (args: A) => infer R ? R : never
// This is the function I want to create
function callFunction<F extends (args: any) => any, A extends Parameters<F>[0]>(
f: F,
args: A,
): ReturnTypeWithArgs<F, A> {
return f(args)
}
// My goal is to have the same return type when using callFunction. Unfortunately, it does not work as intended:
const result2 = callFunction(f, 'test') // KO: typeof test2 is unknown