I have been attempting to declare a generic type based on another generic type but haven't been successful so far.
The main goal is to create my own test framework and define some parameters depending on another parameter (the method).
type Arguments<T> = T extends (...args: infer U) => any ? U : never;
// my custom test method
const methodCall = <T extends (...args: any) => any>(args: {
method: T;
response: ReturnType<T>;
myArguments: Arguments<T>;
}): boolean => {
const { method, myArguments, response } = args;
return method.apply(null, myArguments) === response;
};
const test1 = (toto: string) => {
return toto === "success";
};
// using my custom function
methodCall({
method: test1,
myArguments: ["fail"],
response: false
});
// desired typing for this
interface MyHelpers {
methodCall: any // HOW TO TYPE THIS?
methodCall2: (args: { flag: boolean }) => boolean;
}
// Only exposing the helpers object
const helpers = (): MyHelpers = {
methodCall: <T extends (...args: any) => any>(args: {
method: T;
response: ReturnType<T>;
myArguments: Arguments<T>;
}): boolean => {
const { method, myArguments, response } = args;
return method.apply(null, myArguments) === response;
},
methodCall2: (args: { flag: boolean }): boolean => {
return args.flag;
}
};
When calling helpers from another object, I expect to be able to type helpers().methodCall(...)
as it is declared in helpers, not with any
.
You can access the playground here.
Appreciate your help!