类型 'number' 不可分配给类型 'ReadonlyArray<{}>'

Type 'number' is not assignable to type 'ReadonlyArray<{}>'

完整的 Typescript 错误:

Argument of type '(c: IAsset) => number' is not assignable to parameter of type '(n: IAsset) => ReadonlyArray<{}>'. Type 'number' is not assignable to type 'ReadonlyArray<{}>'.

我的calculatePercentage函数:

// Add coin's percentage of portfolio
export const calculatePercentage = (portfolio: IAsset[], coin: IAsset) => {
  if (coin) {
    portfolio.push(coin);
  }

  const addValue = (c: IAsset) => c.value;
  const values = R.chain(addValue, portfolio);
  const total = values.reduce((acc: number, val: number) => acc + val);

  const updatedPortfolio = portfolio.map((c) => {
    c.percentage = round((c.value / total) * 100);
    return c;
  });

  return updatedPortfolio;
};

使用 addValue 我正在接受一种 IAsset 并返回它的值 (number);

R.chain(addValue, portfolio) 中,addValue 函数然后用于 portfolio 中的每个项目,其类型为 IAsset.

我的界面:

export interface IAsset {
  currency: string;
  exchange: string;
  marketCap: number;
  name: string;
  percentage: number;
  price: number;
  position: number;
  value: number;
}

关于如何在此处正确设置类型的想法?

我对 Ramda 不是很熟悉,但是阅读文档,这似乎可行:

const addValue = (c: IAsset) => [c.value];
const values = R.chain(addValue, portfolio);

但看起来您真正想要使用的是 map

const addValue = (c: IAsset) => c.value;
const values = R.map(addValue, portfolio);

相当于内置的map函数:

const addValue = (c: IAsset) => c.value;
const values = portfolio.map(addValue);

但是你也可以使用reduce来得到总数而无需中间步骤得到values:

const total = portfolio.reduce((acc: number, { value }: IAsset) => acc + value, 0);

我想 Ramda 风格的版本应该是这样的:

var getValue = (c: IAsset) => c.value;
var adder = (a: number, b: number) => a + b;
R.reduce(adder, 0)(R.map(getValue)(portfolio));