【问题标题】:type declaration for array of <key, value> in typescripttypescript 中 <key, value> 数组的类型声明
【发布时间】:2020-08-21 11:39:53
【问题描述】:

对不起,菜鸟问题...

我试图找到声明这种有效类型的“计数”变量的方法。

  const rawData = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

  const getCountData = (rawData: string[]) => {
    const counts: Map<string, number>[] = [];
    rawData.forEach((x: string) => {
      counts[x] = (counts[x] || 0) + 1; 
    });
    
    return Object.values(counts);
  }

使用没有类型声明的纯javascript,结果如下:

[a:3,b:2,c:2,d:2,e:2,f:1,g:1,h:3]

count[x] 抱怨 typescript 中的类型不匹配

Type 'String' 不能用作索引 type.ts(2538)

我可以查看任何参考资料吗?

【问题讨论】:

  • Stringstring 是不同的类型

标签: typescript types


【解决方案1】:

在打字稿中

Map<String, Number>[]

表示一个 Map 数组。从您的代码中,您得到的是地图,而不是地图数组。

您应该使用对象 ({}),而不是数组 ([])。

此外,您可以使用字符串作为键和数字作为值来定义对象

const counts: { [key: string]: number } = {};

您正确输入的整个代码将是:

const getCountData = (rawData: string[]): number[] => {
    const counts: { [key: string]: number } = {};
    rawData.forEach((x: string) => {
      counts[x] = (counts[x] || 0) + 1; 
    });
    
    return Object.values(counts);
  }

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 2021-01-03
  • 2022-11-25
  • 1970-01-01
相关资源
最近更新 更多