Unlike ES6, Typescript doesn’t have its own implementation of maps.

In ES6, you can instantiate maps pretty much the same way as in Java, except you can then use set and get methods to, er, set and get values.

let map = new Map<string,string>();

Typescript does not have this natively. You can bring in an implementation that polyfills this for you (such as typescript-map) but you may not want that overhead. You might also just be trying to store and process data that’s returning from a service as JSON without resorting to any typing.

However, you do have access to the vanilla Javascript object type and Typescript has a method for typing the key and value:

let map : { [index:string], string } = {};
map["key"] = "value";
map.key = "value";

The accessors are then just as an associative array in vanilla Javascript using the array notation, or object notation for keys without invalid characters. Typescript’s of iterator allows you to iterate through the values and in, like Javascript, through the keys.

for( let value of map ) {

Using basic object types lacks some of the nice functional features of the map implementations for ES6 and the typescript polyfill (such as map and filter).

Note that if you’re targeting ES6, then you can use ES6 maps with the correct @types declarations (which are in the Typescript lib.es6.d.ts file), but they are not native to Typescript.

So, if you’re trying to keep the code small, or just trying to type some JSON returning from a service, it’s a useful way to keep strong typings.

Do you have any other good Typescript map tips?