最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TypeScript - How to use array map to an ES 6 Map? - Stack Overflow

programmeradmin0浏览0评论

Lets say I have an array of key value objects:

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

How do I convert it to ES 6 map? It works in JavaScript but TypeScript will complain. Here I got the error of Argument of type 'IterableIterator<string[]>' is not assignable to parameter of type 'ReadonlyArray<[string, string]>'. Property 'length' is missing in type 'IterableIterator<string[]>'.

Lets say I have an array of key value objects:

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

How do I convert it to ES 6 map? It works in JavaScript but TypeScript will complain. Here I got the error of Argument of type 'IterableIterator<string[]>' is not assignable to parameter of type 'ReadonlyArray<[string, string]>'. Property 'length' is missing in type 'IterableIterator<string[]>'.

Share Improve this question edited Nov 27, 2018 at 4:15 Cerlancism asked Nov 27, 2018 at 4:06 CerlancismCerlancism 3,1746 gold badges16 silver badges22 bronze badges 3
  • 1 Just remove the .values() call – dotconnor Commented Nov 27, 2018 at 4:07
  • then it gets Argument of type 'string[][]' is not assignable to parameter of type 'ReadonlyArray<[string, string]>'. Type 'string[]' is not assignable to type '[string, string]'. Property '0' is missing in type 'string[]'. – Cerlancism Commented Nov 27, 2018 at 4:08
  • The problem is in your type declarations. I don't know typescript, but if type declaration is optional, why not just do const ES6Map = new Map(mappedData)? – ba_ul Commented Nov 27, 2018 at 4:13
Add a comment  | 

1 Answer 1

Reset to default 15

You need to do type assertion and tell typescript that your mappedData is of type Array<[string,string]> instead of string[][] which is a sub type for Array<[any,any]> as needed by Map constructor.

Do

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

instead of

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

and also

drop the values() call as pointed out in comments.

发布评论

评论列表(0)

  1. 暂无评论