代码之家  ›  专栏  ›  技术社区  ›  thomas-peter

如何在Typescript中使用compose?

  •  0
  • thomas-peter  · 技术社区  · 7 年前

    const rawHeaders = R.compose(
      R.join('\n'),
      R.map(x=>`${x[0]}: ${x[1]}`),
      R.toPairs
    )
    

    我试过下面的方法,但很残忍。有人知道如何让这件作品更优雅吗?

    const rawHeaders:Function = R.compose(
      R.join('\n'),
      R.map((x:[String, String]) =>`${x[0]}: ${x[1]}`),
      (x:{s:String})=>R.toPairs(x))
    )
    

    const rawHeaders = R.compose(
      R.join('\n'),
      // @ts-ignore
      R.map(x=>`${x[0]}: ${x[1]}`),
      // @ts-ignore
      R.toPairs
    )
    
    0 回复  |  直到 7 年前
        1
  •  10
  •   Peak    7 年前

    你试过利用compose本身的类型吗?您可以为它指定compose中每个函数的参数和返回值,如下所示:

    const rawHeaders = R.compose<
      { [key: string]: string | number }, // Argument
      Array<[string, string]>, // Return of toPairs
      string[], // Return of map
      string // Return of join
    >(
      R.join('\n'),
      R.map(x => `${x[0]}: ${x[1]}`),
      R.toPairs
    );
    

    pipe 因为键入的参数顺序与 ,与 compose 这是向后的:

    const rawHeaders = R.pipe<
      { [key: string]: string | number }, //Argument
      Array<[string, string]>, // return of toPairs
      string[], // return of map
      string // return of join
    >(
      R.toPairs,
      R.map(x => `${x[0]}: ${x[1]}`),
      R.join('\n')
    );
    

    不管是哪种方式,pipe/compose中的每个函数都会得到正确的值,并且您不需要专门修饰pipe中的函数(除非您开始使用类似 R.flip ). 很冗长,但很管用。

    推荐文章