{
"path": "/posts/create-es2015-map-from-array-in-typescript",
"site": "at://did:plc:yy3apqjlms24kso7ahn7lbmb/site.standard.publication/3mova7c4nho2b",
"tags": [
"typescript",
"javascript"
],
"$type": "site.standard.document",
"title": "Creating an ES2015 Map from an Array in TypeScript",
"description": "TypeScript `Map` initialization from an `Array` is discussed with a workaround using a type assertion of ` as [string, string]`.",
"publishedAt": "2016-06-02T00:00:00.000Z",
"textContent": "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.\n\n\n\nThis Doesn't Work\n\nWe're going try to something like this: (pilfered from the MDN docs)\n\nSimple enough right? Well I'd rather assumed that I should be able to do something like this in TypeScript:\n\nHowever, to my surprise this errored out with:\n\nDisappointing right? It's expecting Iterable<[string, string]> and an Array with 2 elements that are strings is _not_ inferred to be that.\n\nThis Does\n\nIt 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.)\n\nSo a working version of the code looks like this:\n\nOr, to be terser, this:\n\nI've raised this as an issue with the TypeScript team; you can find details here.",
"canonicalUrl": "https://johnnyreilly.com/posts/create-es2015-map-from-array-in-typescript"
}