I have some JavaScript code that uses objects as dictionaries; for example a \'person\' object will hold a some personal details keyed off the email address.
In addition to using an map-like object, there has been an actual Map object for some time now, which is available in TypeScript when compiling to ES6, or when using a polyfill with the ES6 type-definitions:
let people = new Map();
It supports the same functionality as Object
, and more, with a slightly different syntax:
// Adding an item (a key-value pair):
people.set("John", { firstName: "John", lastName: "Doe" });
// Checking for the presence of a key:
people.has("John"); // true
// Retrieving a value by a key:
people.get("John").lastName; // "Doe"
// Deleting an item by a key:
people.delete("John");
This alone has several advantages over using a map-like object, such as:
Object
(no, Object
does not support numbers, it converts them to strings)--noImplicitAny
, as a Map
always has a key type and a value type, whereas an object might not have an index-signatureAdditionally, a Map
object provides a more powerful and elegant API for common tasks, most of which are not available through simple Object
s without hacking together helper functions (although some of these require a full ES6 iterator/iterable polyfill for ES5 targets or below):
// Iterate over Map entries:
people.forEach((person, key) => ...);
// Clear the Map:
people.clear();
// Get Map size:
people.size;
// Extract keys into array (in insertion order):
let keys = Array.from(people.keys());
// Extract values into array (in insertion order):
let values = Array.from(people.values());