Understanding TypeScript Maps and Sets: Usage and Operations

Answered using ChatGPT 4o by ChatGPT4o

Question:

typescript maps and sets how they works

Answer:

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:

Map

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.

Basic Operations

  1. Creating a Map:

    let map = new Map<string, number>();
    
  2. Adding Entries:

    map.set("one", 1);
    map.set("two", 2);
    
  3. Getting Values:

    let value = map.get("one"); // 1
    
  4. Checking for Keys:

    let hasKey = map.has("two"); // true
    
  5. Deleting Entries:

    map.delete("one");
    
  6. Clearing the Map:

    map.clear();
    
  7. Iterating Over a Map:

    map.set("one", 1);
    map.set("two", 2);
    
    for (let [key, value] of map) {
        console.log(key, value);
    }
    

Set

A Set is a collection of unique values. Unlike arrays, sets do not allow duplicate values.

Basic Operations

  1. Creating a Set:

    let set = new Set<number>();
    
  2. Adding Values:

    set.add(1);
    set.add(2);
    set.add(2); // Duplicate, will not be added
    
  3. Checking for Values:

    let hasValue = set.has(1); // true
    
  4. Deleting Values:

    set.delete(1);
    
  5. Clearing the Set:

    set.clear();
    
  6. Iterating Over a Set:

    set.add(1);
    set.add(2);
    
    for (let value of set) {
        console.log(value);
    }
    

Differences Between Map and Set

  • Map:

    • Stores key-value pairs.
    • Keys can be of any type.
    • Maintains the order of insertion.
    • Methods: set, get, has, delete, clear, forEach.
  • Set:

    • Stores unique values.
    • Values can be of any type.
    • Maintains the order of insertion.
    • Methods: add, has, delete, clear, forEach.

TypeScript Specifics

TypeScript provides strong typing for Map and Set, which helps catch errors at compile time.

Typed Map Example

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

Typed Set Example

let set = new Set<number>();
set.add(1);
set.add(2);

let hasValue: boolean = set.has(1); // TypeScript knows hasValue is a boolean

Conclusion

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.