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:
Set key/value pairs using the set
method.
Printing a map with console.log
will show all its key/value pairs.
Get a value for a key with the get
method.
If the key doesn’t exist, undefined
is returned.
The size
property returns the number of key/value pairs in the map.
The delete
method removes key/value pairs from a map.
To remove all key/value pairs from a map, use the clear
method.
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 _
.
You can also declare and initialize a new map in one step.
For equality checks on maps, you would typically write a custom function, as there’s no built-in utility function for this in TypeScript.
Note that maps appear in the form Map(2) { 'foo' => 1, 'bar' => 2 }
when printed with console.log
.
Running this TypeScript code will produce similar output showing the keys and values of the map, and demonstrating the map operations outlined above.