没有办法轻易做到这一点,你首先需要一个函数来帮助推理(变量不能声明类型变量)。其次,您需要的重载数量与要支持的函数数量一样多。
解决方案可能如下所示:
function compose<A, R1, R2, R3, R4>(fn1: (a: A) => R1, fn2: (a: R1) => R2, fn3: (a: R2) => R3, fn4: (a: R3) => R4): [typeof fn1, typeof fn2, typeof fn3, typeof fn4]
function compose<A, R1, R2, R3>(fn1: (a: A) => R1, fn2: (a: R1) => R2, fn3: (a: R2) => R3): [typeof fn1, typeof fn2, typeof fn3]
function compose<A, R1, R2>(fn1: (a: A)=> R1, fn2: (a: R1) => R2) : [typeof fn1, typeof fn2]
function compose(...fns: Array<(a: any) => any>) {
return fns;
}
// fns is [(a: string) => string, (a: string) => number, (a: number) => string]
let fns = compose(
(s: string) => s.toUpperCase(),
s => +s,
n => n.toExponential()
)