Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  161] [ 3]  / answers: 1 / hits: 16859  / 6 Years ago, tue, november 27, 2018, 12:00:00

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


More From » typescript

 Answers
17

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.


[#53035] Thursday, November 22, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lucianom

Total Points: 601
Total Questions: 98
Total Answers: 109

Location: Kenya
Member since Fri, Dec 23, 2022
1 Year ago
lucianom questions
Tue, Feb 22, 22, 00:00, 2 Years ago
Wed, May 5, 21, 00:00, 3 Years ago
Sun, Jan 24, 21, 00:00, 3 Years ago
Sat, Aug 15, 20, 00:00, 4 Years ago
Mon, Jun 22, 20, 00:00, 4 Years ago
;