【问题标题】:Type 'number' is not assignable to type 'ReadonlyArray<{}>'类型 'number' 不可分配给类型 'ReadonlyArray<{}>'
【发布时间】:2019-02-22 21:38:36
【问题描述】:

完整的打字稿错误:

'(c: IAsset) => number' 类型的参数不可分配给'(n: IAsset) => ReadonlyArray' 类型的参数。 类型 'number' 不可分配给类型 '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;
}

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

【问题讨论】:

  • This answer 可能会阐明链和地图之间的区别。

标签: javascript typescript ramda.js


【解决方案1】:

我对 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));

【讨论】:

  • 谢谢! 100% 欣赏这个!由于我对 Ramda 的热爱,我想我的功能过于复杂了哈哈
猜你喜欢
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 2023-01-22
  • 2017-01-05
  • 2021-01-20
  • 2022-01-16
  • 2021-12-05
相关资源
最近更新 更多