Absolutely! It is feasible to achieve this task. The key lies in implementing recursive array traversal within your generic functions to iterate through the ReturnValues array and construct parameters for the callback function.
Feel free to inquire if you need further elucidation on any aspect, as there's quite a bit to unpack here!
function returnValue<K extends string, T>(key: K, type: T): [K, T] {
return [key, type];
}
type ReturnValue = ReturnType<typeof returnValue>;
type GenerateCallbackParams<I extends readonly ReturnValue[], P = {}> =
// Base case where we have one item left in I
I extends readonly [infer R]
? R extends [infer K, infer T]
? K extends string
// Merge params with K: T
? P & { [key in K]: T }
: P
: never
// Handling multiple array elements in I
: I extends readonly [infer R, ...(infer Tail)]
? R extends [infer K, infer T]
? K extends string
? Tail extends ReturnValue[]
? GenerateCallbackParams<Tail, P & { [key in K]: T }>
: never
: never
: never
: never;
function arbitraryFunction<I extends readonly ReturnValue[]>(inputParams: I, callback: (params: GenerateCallbackParams<I>) => GenerateCallbackParams<I>) {
}
// Declaration of const is necessary to prevent TS from changing the type inside the array
const params = [
returnValue("key1", "a"),
returnValue("key2", 1),
returnValue("key3", ()=>{})
] as const;
arbitraryFunction(
// Dynamically generated input
params,
// Callback function with typed parameters based on input
({ key1, key2, key3}) => {
typeof key1; // string
typeof key2; // number
typeof key3; // () => void
return { key1, key2, key3 };
}
)
Navigate to playground