Creating an ES2015 Map from an Array in TypeScript
I'm a great lover of ES2015's Map. However, just recently I tumbled over something I find a touch inconvenient about how you initialise a new Map from the contents of an Array in TypeScript.
This Doesn't Work
We're going try to something like this: (pilfered from the MDN docs)
Simple enough right? Well I'd rather assumed that I should be able to do something like this in TypeScript:
However, to my surprise this errored out with:
Disappointing right? It's expecting Iterable<[string, string]> and an Array with 2 elements that are strings is not inferred to be that.
This Does
It emerges that there is a way to do this though; you just need to give the compiler a clue. You need to include a type assertion of as [string, string] which tells the compiler that what you've just declared is a Tuple of string and string. (Please note that [string, string] corresponds to the types of the Key and Value of your Map and should be set accordingly.)
So a working version of the code looks like this:
Or, to be terser, this:
I've raised this as an issue with the TypeScript team; you can find details here.
Discussion in the ATmosphere