Maps in TypeScript

Maps are TypeScript’s built-in associative data type (sometimes called hashes or dicts in other languages).

To create an empty map, use the new keyword with the Map class:

const m: Map<string, number> = new Map();

Set key/value pairs using the set method.

m.set("k1", 7);
m.set("k2", 13);

Printing a map with console.log will show all its key/value pairs.

console.log("map:", m);

Get a value for a key with the get method.

const v1: number | undefined = m.get("k1");
console.log("v1:", v1);

If the key doesn’t exist, undefined is returned.

const v3: number | undefined = m.get("k3");
console.log("v3:", v3);

The size property returns the number of key/value pairs in the map.

console.log("len:", m.size);

The delete method removes key/value pairs from a map.

m.delete("k2");
console.log("map:", m);

To remove all key/value pairs from a map, use the clear method.

m.clear();
console.log("map:", m);

The optional second return value when getting a value from a map indicates if the key was present. This can be used to disambiguate between missing keys and keys with zero values like 0 or "". Here we didn’t need the value itself, so we ignored it with the blank identifier _.

const prs: boolean = m.has("k2");
console.log("prs:", prs);

You can also declare and initialize a new map in one step.

const n: Map<string, number> = new Map([["foo", 1], ["bar", 2]]);
console.log("map:", n);

For equality checks on maps, you would typically write a custom function, as there’s no built-in utility function for this in TypeScript.

const n2: Map<string, number> = new Map([["foo", 1], ["bar", 2]]);
const mapsEqual = (map1: Map<string, number>, map2: Map<string, number>): boolean => {
    if (map1.size !== map2.size) {
        return false;
    }
    for (const [key, value] of map1) {
        if (value !== map2.get(key)) {
            return false;
        }
    }
    return true;
};
if (mapsEqual(n, n2)) {
    console.log("n == n2");
}

Note that maps appear in the form Map(2) { 'foo' => 1, 'bar' => 2 } when printed with console.log.

console.log("map:", m);

Running this TypeScript code will produce similar output showing the keys and values of the map, and demonstrating the map operations outlined above.