我有一个可以进行curry(函数式编程)的函数,我将其声明如下:
declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): (index: number, list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): (index: number) => (list: T[]) => T[];
但在这种情况下,最后一行代码将无法工作,因为它与倒数第二行具有相同的参数。
我也考虑Union Types
,就像:
declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): ((index: number, list: T[]) => T[]) | ((index: number) => (list: T[]) => T[]);
但它会导致ts
错误:
TS2349:Cannot invoke an expression whose type lacks a call signature. Type '((index: number, list: number[]) => number[]) | ((index: number) => (list: number[]) => number[])' has no compatible call signatures
那么,我该如何纠正呢?
答案 0 :(得分:1)
您可以使用带有调用签名的接口作为最后一个函数的返回类型:
declare interface AdjustReturnFunction<T>{
(index: number, list: T[]): T[];
(index: number): (list: T[]) => T[];
}
declare function adjust<T>(fn: (a: T) => T, index: number, list: T[]): T[];
declare function adjust<T>(fn: (a: T) => T, index: number): (list: T[]) => T[];
declare function adjust<T>(fn: (a: T) => T): AdjustReturnFunction<T>;