如何在Typescript中使用compose?

问题描述 投票:1回答:1

我在使用Typescript中的compose时遇到问题....

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

我也试过使用ts-ignore,目前看来这是最好的选择。

const rawHeaders = R.compose(
  R.join('\n'),
  // @ts-ignore
  R.map(x=>`${x[0]}: ${x[1]}`),
  // @ts-ignore
  R.toPairs
)
typescript ramda.js
1个回答
1
投票

你是否尝试过利用自己的输入法?您可以在组合中为其提供参数和每个函数的返回值,如下所示:

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作为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')
);

无论哪种方式,管道/撰写中的每个函数都获得正确的值,您不需要专门在管道中装饰该函数(除非您开始使用类似R.flip的东西)。它很冗长,但它确实有效。

(你可以为第一个函数指定所需数量的args,重载将处理其余的btw)

© www.soinside.com 2019 - 2024. All rights reserved.