【发布时间】:2019-12-27 00:38:54
【问题描述】:
我正在尝试基于另一个泛型类型声明一个泛型类型,但没有成功。
目标是编写我自己的测试框架并根据另一个(方法)键入一些参数。
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";
};
// usage of my custom function
methodCall({
method: test1,
myArguments: ["fail"],
response: false
});
// this is what I want to type
interface MyHelpers {
methodCall: any // HOW TO TYPE THIS?
methodCall2: (args: { flag: boolean }) => boolean;
}
// I would expose only 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;
}
};
我期望另一个调用助手的对象能够使用 helpers().methodCall(...) 来键入,因为它在助手中声明。不是any。
操场可以在here 找到。
谢谢!
【问题讨论】:
标签: typescript typescript-typings typescript-generics