typescript maps and sets how they works
In TypeScript, Map
and Set
are part of the ES6 (ECMAScript 2015) standard and provide more flexible and efficient ways to handle collections of data compared to traditional objects and arrays. Here's a detailed look at how they work:
A Map
is a collection of key-value pairs where the keys can be of any type. This is different from a regular JavaScript object, where keys are always strings or symbols.
Creating a Map:
let map = new Map<string, number>();
Adding Entries:
map.set("one", 1);
map.set("two", 2);
Getting Values:
let value = map.get("one"); // 1
Checking for Keys:
let hasKey = map.has("two"); // true
Deleting Entries:
map.delete("one");
Clearing the Map:
map.clear();
Iterating Over a Map:
map.set("one", 1);
map.set("two", 2);
for (let [key, value] of map) {
console.log(key, value);
}
A Set
is a collection of unique values. Unlike arrays, sets do not allow duplicate values.
Creating a Set:
let set = new Set<number>();
Adding Values:
set.add(1);
set.add(2);
set.add(2); // Duplicate, will not be added
Checking for Values:
let hasValue = set.has(1); // true
Deleting Values:
set.delete(1);
Clearing the Set:
set.clear();
Iterating Over a Set:
set.add(1);
set.add(2);
for (let value of set) {
console.log(value);
}
Map:
set
, get
, has
, delete
, clear
, forEach
.Set:
add
, has
, delete
, clear
, forEach
.TypeScript provides strong typing for Map
and Set
, which helps catch errors at compile time.
let map = new Map<string, number>();
map.set("one", 1);
map.set("two", 2);
let value: number | undefined = map.get("one"); // TypeScript knows value is a number or undefined
let set = new Set<number>();
set.add(1);
set.add(2);
let hasValue: boolean = set.has(1); // TypeScript knows hasValue is a boolean
Map
and Set
are powerful data structures in TypeScript that provide more flexibility and efficiency compared to traditional objects and arrays. They come with a rich set of methods for managing collections of data, and TypeScript's type system ensures that you can use them safely and effectively.