[英]Inferring generic type parameter based on another generic parameter in TypeScript
[英]Type object parameter based on another generic parameter
我正在尝试根据打字稿中的另一个通用参数动态键入一个参数。
这是为了构建一个自定义测试框架,该框架将要测试的方法、其参数和预期结果作为参数。
// 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
};
但是我想找到一种根据传入参数的方法的参数来输入参数和响应的方法。
先感谢您!
你真的很接近解决方案! 通过一些小的调整,这个编译和类型检查。 您必须确保将泛型类型参数添加到myCustomTest
函数中:
type Arguments<T> = T extends (...args: infer U) => any ? U : never;
const myCustomTest = <T extends (...args: any) => any>(arg: { method: T, parameters: Arguments<T>, response: ReturnType<T>}) => {
const { method, parameters, response } = arg;
return method.apply(null, parameters) === response; // suppose this is a sync function
};
请参阅此 Typescript Playground 中的完整示例!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.