【问题标题】:TypeScript - How to use array map to an ES 6 Map?TypeScript - 如何使用数组映射到 ES 6 映射?
【发布时间】:2018-11-27 04:06:17
【问题描述】:

假设我有一个键值对象数组:

const data = [
    {key: "object1", value: "data1"},
    {key: "object2", value: "data2"},
    {key: "object3", value: "data3"},
]

const mappedData = data.map(x => [x.key, x.value]);

const ES6Map = new Map<string, string>(mappedData.values())

如何将其转换为 ES 6 地图?它适用于 JavaScript,但 TypeScript 会抱怨。这里我得到了Argument of type 'IterableIterator<string[]>' is not assignable to parameter of type 'ReadonlyArray<[string, string]>'. Property 'length' is missing in type 'IterableIterator<string[]>'.的错误

【问题讨论】:

  • 只需删除.values() 调用
  • 然后得到Argument of type 'string[][]' is not assignable to parameter of type 'ReadonlyArray&lt;[string, string]&gt;'. Type 'string[]' is not assignable to type '[string, string]'. Property '0' is missing in type 'string[]'.
  • 问题出在你的类型声明中。我不知道打字稿,但如果类型声明是可选的,为什么不直接做const ES6Map = new Map(mappedData)?

标签: javascript typescript dictionary ecmascript-6


【解决方案1】:

您需要执行 type assertion 并告诉 typescript 您的 mappedData 是 Array&lt;[string,string]&gt; 类型,而不是 string[][],它是 Array&lt;[any,any]&gt; 的子类型 Map 构造函数所需要的。

做

const mappedData = data.map(x => [x.key, x.value] as [string, string]);

而不是

const mappedData = data.map(x => [x.key, x.value]);

还有

如 cmets 中所指出的,放弃 values() 调用。

【讨论】:

  • 在这些示例中x 的类型是什么?
猜你喜欢
  • 2018-06-18
  • 1970-01-01
  • 2017-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多