Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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[]>'.

like image 227
Cerlancism Avatar asked Nov 27 '18 04:11

Cerlancism


1 Answers

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.

like image 54
vibhor1997a Avatar answered Oct 25 '22 08:10

vibhor1997a