Sets
What
A Set is a built-in JavaScript collection that stores unique values. TypeScript allows you to specify the type of values the set can contain using a type parameter <T>.
How
You can initialize a set and use methods like add, has, and delete to manage its contents:
const justiceLeague = new Set<string>();
justiceLeague.add("Flash");
justiceLeague.add(2); // Error: Argument of type 'number' is not assignable to 'string'
// Deduplicate an array
const names = ["plasticman", "firestorm", "plasticman"];
const uniqueNames = new Set<string>(names); // Set { 'plasticman', 'firestorm' }
Why
Sets are ideal for scenarios where you need to ensure no duplicate data exists, such as a list of unique user IDs or tags. They also offer better performance than arrays for checking if an item exists (has).
Summary
Use Set<T> for collections where uniqueness is required and fast lookups are a priority.