【问题标题】:Typescript: Mapped array to sequential function in/output打字稿:将数组映射到顺序函数输入/输出
【发布时间】:2019-01-18 11:04:15
【问题描述】:

在 Typescript 中,有没有办法用以下属性来表示数组?

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

基本上,一个函数数组,其中下一个函数接受最后一个函数的返回值。我想将它用于 Koa 路由器,其中可以提供一组中间件。这样,可以在一个中间件函数中验证输入,然后在下一个函数中使用而无需强制转换。

【问题讨论】:

    标签: typescript koa


    【解决方案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()
    )
    

    【讨论】:

    • 这就是我所担心的......无论如何,谢谢!
    猜你喜欢
    • 2022-11-29
    • 2021-10-10
    • 2020-12-17
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    • 2015-04-20
    • 1970-01-01
    相关资源
    最近更新 更多