TypeScript and map

We discussed creating a dictionary/set with the index signature that leverages the flexibility of an object. An alternative is the use of a map class. A map is a class that can be instantiated with or without values, and it is a type of object that is not unique to TypeScript. ECMAScript defines how a map is structured and behaves; TypeScript is providing a type on top of the class.

A map has the same capability of fast access than index signature. The following code instantiates the Map with two key-values entries. The key and the value can be anything. What is important in the constructor is when providing a value, this one must be iterable:

let map = new Map([["key1", "value1"], ["key2", "value2"]]);

let value1: string | undefined = map.get("key1");

The previous code not only created a map but also accessed a value by using a key of the same type as defined in the constructor. If a key does not exist in the map, an undefined value is returned, similar to the index signature. The next code example creates two maps, without providing initial values. The first one doesn't use the generic definition; hence, falls back to the type any for the key and the value. However, the second line shows an initialization that specifies the generic type to have a key of string and a value of a number. Even if the map does not have values specified at the initialization, the latter still provides a strongly typed enforcement for a future value set by the function set:

let map2 = new Map(); // Key any, value any
let map3 = new Map<string, number>(); // Key string, value number

The following code does not compile because the key type must be the same. In the code example, it has a number and a string:

let map4 = new Map([[1, "value1"], ["key2", "value2"]]); // Doesn't compile

A map has many functions other than get. It can set values, which is handy when you do not have all the values of the creation of the map. A map can also look up to see whether a key exists in the map by returning true or false. Finally, it is possible to remove an entry with a function instead of relying on the delete keyword for an index signature:

map.set("key3", "value3");
map.has("key1");
map.delete("key1"); // Similar to delete obj.key1 (index signature)
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.220.245.233