根据另一个通用参数输入对象参数

时间:2019-08-20 14:16:44

标签: typescript typescript-typings typescript-generics

我正在尝试根据打字稿中的另一个通用参数动态键入一个参数。

这是要构建一个自定义测试框架,该框架将要测试的方法,其参数和预期结果作为参数。

// 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
};

但是我想找到一种方法来键入参数和响应,具体取决于传入参数的方法的参数。

提前谢谢!

1 个答案:

答案 0 :(得分:1)

您真的很接近解决方案!通过一些小的调整,可以编译并检查类型。您必须确保在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
};

this Typescript Playground中查看完整示例!

相关问题