打字稿:映射数组到顺序功能输入/输出

时间:2019-01-18 11:04:15

标签: typescript koa

在Typescript中,有没有一种方法可以表达具有以下属性的数组?

[
  [0]: function(in: A): B;
  [1]: function(in: B): C;
  [2]: function(in: C): D;
  ...etc.
]

基本上是一个函数数组,其中下一个函数接受最后一个的返回值。我想将其用于Koa路由器,可以在其中提供一系列中间件。这样,可以在一个中间件功能中验证输入,然后在不强制转换的情况下使用该输入。

1 个答案:

答案 0 :(得分:1)

无法轻松地做到这一点,首先需要一个函数来帮助进行推理(变量不能声明类型变量)。其次,您需要与要支持的功能数量一样多的重载。

解决方案可能看起来像这样:

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()
)