I'm creating a class in typescript that has a property that is an ES6 (ECMAscript 2016) Map like so:
class Item { configs: ????; constructor () { this.configs = new Map(); } }
How do I declare an ES6 Map type in typescript?
TypeScript does support Maps "natively" now, so it simply allows ES6 Maps to be used when the output is ES6.
Creating a MapUse Map type and new keyword to create a map in TypeScript. let myMap = new Map<string, number>(); To create a Map with initial key-value pairs, pass the key-value pairs as an array to the Map constructor.
ES6 provides us a new collection type called Map, which holds the key-value pairs in which values of any type can be used as either keys or values. A Map object always remembers the actual insertion order of the keys. Keys and values in a Map object may be primitive or objects. It returns the new or empty Map.
EDIT (Jun 5 2019): While the idea that "TypeScript supports Map
natively" is still true, since version 2.1 TypeScript supports something called Record
.
type MyMapLikeType = Record<string, IPerson>; const peopleA: MyMapLikeType = { "a": { name: "joe" }, "b": { name: "bart" }, };
Unfortunately the first generic parameter (key type) is still not fully respected: even with a string
type, something like peopleA[0]
(a number
) is still valid.
EDIT (Apr 25 2016): The answer below is old and should not be considered the best answer. TypeScript does support Maps "natively" now, so it simply allows ES6 Maps to be used when the output is ES6. For ES5, it does not provide polyfills; you need to embed them yourself.
For more information, refer to mohamed hegazy's answer below for a more modern answer, or even this reddit comment for a short version.
As of 1.5.0 beta, TypeScript does not yet support Maps. It is not yet part of the roadmap, either.
The current best solution is an object with typed key and value (sometimes called a hashmap). For an object with keys of type string
, and values of type number
:
var arr : { [key:string]:number; } = {};
Some caveats, however:
string
or number
With the above example:
// OK: arr["name"] = 1; // String key is fine arr[0] = 0; // Number key is fine too // Not OK: arr[{ a: "a" }] = 2; // Invalid key arr[3] = "name"; // Invalid value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With