打字稿灵活的“ thunked”功能

时间:2018-10-19 08:08:14

标签: typescript

假设我有一个“ thunked”方法:

createToDoMethodWithConversion<T1,T2>(getOutputOfTypeA: (val1: T1, val2: T2) => TA): (val1: T1, val2: T2) => TB {
     return (val1: T1, val2: T2) => {
       const item: TA = getOutputOfTypeA(val1, val2);
       return this.doSeriousConversionBusiness(item); // convert to TB
     };
}

我该如何灵活地执行以下操作:

const newMethod: (val1: T1, val2: T2, val3: T3) => TB
  = createToDoMethodWithConversion<T1,T2,T3>(getX: (val1: T1, val2: T2, val3: T3) => TA)

或者这个:

const newMethod: (val1: T1, val2: T2, val3: T3, val4: T4) => TB
  = createToDoMethodWithConversion<T1,T2,T3,T4>(getX: (val1: T1, val2: T2, val3: T3, val4: T4) => TA)

1 个答案:

答案 0 :(得分:0)

从TypeScript 3.0开始,您可以使用tuple types in rest/spread positions。这样,您就可以使用单个通用类型参数来表示函数的参数列表:

createToDoMethodWithConversion<T extends any[]>(
  getOutputOfTypeA: (...val: T) => TA
): (...vals: T) => TB {
  return (...vals: T) => {
    const item: TA = getOutputOfTypeA(...vals);
    return this.doSeriousConversionBusiness(item); // convert to TB
  };
}

请注意在函数定义中使用rest参数,在函数调用中使用类似的spread参数。让我们看看它是否有效:

const x = new Foo(); // class containing createToDoMethodWithConversion method
declare const f3: (x: string, y: number, z: boolean) => TA;
const newF3 = x.createToDoMethodWithConversion(f3) // (x: string, y: number, z: boolean) => TB;
declare const f4: (x: string, y: number, z: boolean, w?: RegExp) => TA;
const newF4 = x.createToDoMethodWithConversion(f4) // (x: string, y: number, z: boolean, w?: RegExp) => TB;

对我很好。希望能有所帮助;祝你好运!