let myMap = new Map([
["😀", "smiley face"],
["👽", "alien"],
["🦄", "unicorn"]
]);
// Convert map back to array
let asArray = [...myMap];
// Log array to console.
// This is the same format as the map was
// initialised with, i.e.:
// [
// ["😀", "smiley face"],
// ["👽", "alien"],
// ["🦄", "unicorn"]
// ]
console.log("Map converted to array: ", asArray);
Once again TypeScript correctly infers the type of the array depending on the type of the Map. However you might notice the array type is [string, string][]
. Remember that in the type of an array, the type of the elements comes before []
. So this means that the type of the elements are [string, string]
, which means an array with exactly two elements, both of which are strings. So the overall type of the array is "an array of two-element arrays with each element being a string".
The generic Array type
There's one last thing to note: for consistency with other types, you can also use the generic syntax with arrays. The type Array<string>
means the same thing as string[]
.
Conclusion
In this part we've covered:
- Creating arrays, accessing array elements, and reading the array length
- Iterating arrays with both for loops and for-of loops
- Adding and removing array elements
- Creating sets, adding and removing set values, and reading the set size
- Iterating sets, and converting sets back to arrays
- Creating maps, adding and removing keys and values, and retrieving values from keys
- Different ways to iterate maps, and converting maps back to arrays
These data structures come in useful with day-to-day programming in TypeScript, so it's good to get familiar with how they work. In particular arrays are very common, so if you want to focus on one area, focus on them.
We've touched on a few built-in features of TypeScript in this guide so far. In the next part we'll focus on covering more built-ins, including some of the many features that browsers provide.
Learn more
If you want to dig deeper, you can learn more about the features mentioned in this guide at the following MDN Web Docs links: