【发布时间】:2019-08-20 22:28:33
【问题描述】:
我正在尝试根据打字稿中的另一个通用参数动态键入参数。
这是为了构建一个自定义测试框架,将测试方法、其参数和预期结果作为参数。
// function that tests if the method return an expected result
const myCustomTest = (arg: { method: (...arg: any[]) => any, arguments: any, response: any }) => {
const { method, arguments, response } = arg;
return method.apply(null, arguments) === response; // suppose this is a sync function
};
// given a function test1
const test1 = (arg: number, arg2: boolean): boolean => {
return true;
};
// then the linter should raise
myCustomTest({ method: test1, arg: [12, 12], response: true }); // wrong, second parameter is a number and not a boolean
myCustomTest({ method: test1, arg: [12, false], response: true }); // OK
// It could work with
type Arguments<T> = T extends (...args: infer U) => any ? U : any;
const myCustomTest = (arg: { method: (...arg: any[]) => any, arguments: Arguments<typeof test1>, response: ReturnType<typeof test1> }) => {
const { method, arguments, response } = arg;
return method.apply(null, arguments) === response; // suppose this is a sync function
};
但我想根据传入参数的方法的参数找到一种输入参数和响应的方法。
提前谢谢你!
【问题讨论】:
标签: typescript typescript-typings typescript-generics