【问题标题】:Type object parameter based on another generic parameter基于另一个泛型参数的类型对象参数
【发布时间】: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


    【解决方案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中的完整示例!

    【讨论】:

      猜你喜欢
      • 2020-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-04
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多