Within my functions.ts file, I have defined 2 functions. Each of these functions accepts an api
object and returns a function with varying argument types, numbers, and return types.
export function f1 (api: Api) {
return function (a: number): number[] {/* not important */}
};
export function f2 (api: Api) {
return function (a: string, b: string): boolean {/* not important */}
};
Now, with a global api: Api
object, I aim to create an object that includes the fields f1
and f2
, with each field holding the inner function from the aforementioned functions.
Manually, this can be achieved as follows:
const api: Api = ...;
const myObject = {
f1: f1(api),
f2: f2(api),
}
This manual method works perfectly.
However, the next challenge is to achieve this dynamically, without explicitly typing out f1 and f2.
Here is my initial attempt:
import * as functions from './functions';
const api: Api = ...;
const myObject = Object.keys(functions).reduce((accumulator, functionName) => {
accumulator[functionName] = functions[functionName](api);
}, {} as ???);
The code functions correctly, but the typings are incorrect. I am unsure what to input instead of ???
. Using
{[index: keyof typeof functions]: (...args: any[]) => any}
would work, but it would result in losing type information.
I have explored TypeScript's Parameters<T>
and ReturnType<T>
, and suspect that there may be a solution involving infer
, but I am struggling to grasp it.