In an attempt to create a wrapper function that takes a function as input and returns a new typed function that allows for both a list of parameters and an object containing parameter names as keys.
I have developed the following code, which functions as expected. The issue lies in the fact that I am required to pass an additional type with keys representing parameter names and their corresponding types. My aim is to achieve this dynamically, by accessing the parameter names.
//I want to eliminate the Args parameters and make it dynamic using F type.
function wrapper<F extends (...args: any) => any, Args>(func: unknown) {
type ParametersList = Parameters<F>;
return func as (...args: [Args] | ParametersList) => ReturnType<F>;
}
const add = (x: number, y: number) => x + y;
const wrappedAdd = wrapper<typeof add, { x: number; y: number }>(add);
The Parameters
function retrieves a named tuple (a new feature, I believe). Is there a method to obtain the names/labels of that tuple? Your suggestions are welcome.
###Edit:
After some investigation, I discovered that it's not possible to retrieve the parameter names of a function. Therefore, my objective now is to streamline the code. Instead of passing an object in place of Args
, I prefer to simply pass an array of strings.
const wrappedAdd = wrapper<typeof add, ["x", "y"]>(add);
I intend to dynamically generate an object using this array. Thank you.