JavaScript has two built-in collection types that often get overlooked in favor of plain arrays and objects: Set and Map. Here’s when and how to use them.

Using Sets in TypeScript

A Set stores unique values — duplicates are silently ignored. Here’s the basic API:

const mySet = new Set<number>();

mySet.add(1);
mySet.add(2);
mySet.add(3);
mySet.add(1); // Duplicate value is ignored

console.log(mySet.has(1)); // Output: true
console.log(mySet.size); // Output: 3

mySet.delete(2);

console.log(mySet.size); // Output: 2

mySet.clear();

console.log(mySet.size); // Output: 0

Common use cases for Sets

The most common one — removing duplicates from an array:

const myArray = [1, 2, 2, 3, 3, 3];
const mySet = new Set(myArray);
const uniqueArray = Array.from(mySet);

console.log(uniqueArray); // Output: [1, 2, 3]

Sets also make union, intersection, and difference operations readable:

const setA = new Set([1, 2, 3]);
const setB = new Set([2, 3, 4]);

const union = new Set([...setA, ...setB]);
const intersection = new Set([...setA].filter(x => setB.has(x)));
const difference = new Set([...setA].filter(x => !setB.has(x)));

console.log(union); // Output: Set(4) {1, 2, 3, 4}
console.log(intersection); // Output: Set(2) {2, 3}
console.log(difference); // Output: Set(1) {1}

Using Maps in TypeScript

A Map stores key-value pairs with a cleaner API than plain objects — and keys can be any type, not just strings:

const myMap = new Map<string, number>();

myMap.set('one', 1);
myMap.set('two', 2);
myMap.set('three', 3);

console.log(myMap.get('two')); // Output: 2
console.log(myMap.has('four')); // Output: false
console.log(myMap.size); // Output: 3

myMap.delete('three');

console.log(myMap.size); // Output: 2

myMap.clear();

console.log(myMap.size); // Output: 0

Common use cases for Maps

Maps work better than plain objects when keys are dynamic, insertion order matters, or keys aren’t strings.

type User = { id: number; name: string };

const users = new Map<number, User>();
users.set(1, { id: 1, name: 'Alice' });
users.set(2, { id: 2, name: 'Bob' });

console.log(users.get(1)?.name); // Output: 'Alice'
console.log(users.has(3)); // Output: false

Compared to plain objects, Map provides a cleaner API for frequent insertions/deletions and supports keys of any type.

Conclusion

Use Set for unique values, Map for key-value storage where you need non-string keys or care about insertion order.