TYPESCRIPT
TypeScript Set Object: Syntax, Usage, and Examples
A Set object stores a collection of values where each value can appear only once. Set is great for removing duplicates, tracking membership fast, and keeping your code clean.
How to Use a Set object
A Set is built into JavaScript, so TypeScript uses the same API, you just get better types on top of it.
Learn TypeScript on Mimo
Basic syntax
const mySet =newSet();
That works, but TypeScript won’t know what type of values you plan to store. Most of the time, you’ll want a typed version.
Create a typed Set
constuserIds:Set<number> =newSet();
userIds.add(101);
userIds.add(102);
Now TypeScript knows the Set holds numbers only.
Create a Set from an array
Passing an array into the constructor is a common move:
const colors = ["purple","blue","purple","green"];
const colorSet =newSet(colors);
console.log(colorSet);// Set { 'purple', 'blue', 'green' }
The duplicates disappear because a Set only keeps one copy of each value.
Common methods you’ll use
These are the core methods you’ll reach for all the time:
const visitedPages =newSet<string>();
visitedPages.add("/home");
visitedPages.add("/pricing");
console.log(visitedPages.has("/home"));// true
console.log(visitedPages.size);// 2
visitedPages.delete("/pricing");
visitedPages.clear();
Quick cheat sheet:
add(value)adds a valuehas(value)checks if a value existsdelete(value)removes a valueclear()removes everythingsizetells you how many values are inside
Loop through a Set
A Set is iterable, so you can use for...of:
const tags =newSet<string>(["frontend","css","typescript"]);
for (const tagof tags) {
console.log(tag);
}
You can also use forEach:
tags.forEach((tag) =>console.log(tag));
When to Use a Set object
A Set shines when you care about “is this value already in here?” and you don’t want duplicates messing things up.
1) Removing duplicates from a list
A Set is one of the cleanest ways to deduplicate:
const numbers = [1,2,2,3,3,3];
const uniqueNumbers = [...newSet(numbers)];
console.log(uniqueNumbers);// [1, 2, 3]
No loops, no manual checks, no extra logic.
2) Fast membership checks
Checking an array for a value gets slower as the list grows, because it scans through items. A Set checks membership much faster.
const blockedUsernames =newSet<string>(["bot123","spammy","fakeUser"]);
functionisBlocked(username:string):boolean {
return blockedUsernames.has(username);
}
This is great for things like:
- blocked IDs
- feature flags
- permission keys
- “already processed” items
3) Tracking visited or processed items
Any time you want to avoid doing the same work twice, a Set is a great way to handle it.
const processedOrders =newSet<string>();
functionprocessOrder(orderId:string) {
if (processedOrders.has(orderId))return;
processedOrders.add(orderId);
console.log(`Processing order ${orderId}...`);
}
This pattern keeps your system from repeating actions, even if the same ID shows up again.
4) Building a “toggle” style selection
Sets are perfect for UI selection states, like selecting multiple items:
const selectedFilters =newSet<string>();
functiontoggleFilter(filterName:string) {
if (selectedFilters.has(filterName)) {
selectedFilters.delete(filterName);
}else {
selectedFilters.add(filterName);
}
}
That’s a clean way to model multi-select filters in apps.
Examples of a Set object
Let’s use the Set object in a few real-ish scenarios you’ll recognize.
Example 1: Deduplicate search history
Implementing a search bar that saves recent searches but keeps them clean:
const searches = ["react","typescript","react","css","typescript"];
const searchHistory =newSet(searches);
console.log([...searchHistory]);// ['react', 'typescript', 'css']
A Set keeps the history tidy without you doing extra work.
If you want to add new searches later:
searchHistory.add("node");
searchHistory.add("css");// already there, no duplicate added
Example 2: Check if a username is taken
Implementing a list of reserved usernames:
const reservedNames =newSet<string>(["admin","support","root"]);
functioncanUseName(name:string):boolean {
return !reservedNames.has(name.toLowerCase());
}
console.log(canUseName("Support"));// false
console.log(canUseName("Lina"));// true
This reads nicely, and it’s fast.
Example 3: Keep track of online players
Here’s a multiplayer-style example, tracking who is online:
const onlinePlayers =newSet<string>();
functionplayerJoined(username:string) {
onlinePlayers.add(username);
}
functionplayerLeft(username:string) {
onlinePlayers.delete(username);
}
playerJoined("Nova");
playerJoined("Kai");
playerJoined("Nova");// duplicate ignored
console.log(onlinePlayers.size);// 2
console.log(onlinePlayers.has("Kai"));// true
Sets help you avoid weird cases like the same player being “online” twice.
Example 4: Find common elements between two lists
Sets make intersections simple. Let’s find shared interests between two people:
const samInterests =newSet(["music","hiking","photography"]);
const devInterests =newSet(["gaming","hiking","music"]);
constcommon:string[] = [];
for (const interestof samInterests) {
if (devInterests.has(interest)) {
common.push(interest);
}
}
console.log(common);// ['music', 'hiking']
This is a common “filter with membership” pattern.
Learn More About a Set object
Once you know the basics, you’ll start noticing little details that matter in real TypeScript projects.
Set vs Array
An array is great when:
- order matters
- duplicates matter
- you need indexing (
items[0])
A Set is great when:
- duplicates should be ignored
- membership checks matter
- you want clean “unique values only” behavior
You can always convert between them:
const myArray = [1,2,2,3];
const mySet =newSet(myArray);
const backToArray =Array.from(mySet);
console.log(backToArray);// [1, 2, 3]
Set vs Map
These two are often mentioned together, but they solve different problems:
- A Set stores values only:
Set<string> - A Map stores key-value pairs:
Map<string, number>
If you find yourself doing something like storing a value for each item, Map is usually the better tool.
Example:
const loginCount =newMap<string,number>();
loginCount.set("Maya",5);
loginCount.set("Maya", (loginCount.get("Maya") ??0) +1);
A Set can’t do that, because it has no keys.
Sets don’t store duplicates, but objects behave differently
This surprises people at first.
For primitive values, duplicates are easy:
const nums =newSet<number>();
nums.add(1);
nums.add(1);
console.log(nums.size);// 1
For objects, Sets check reference identity, not “deep equality”:
const a = {id:1 };
const b = {id:1 };
const users =newSet<object>();
users.add(a);
users.add(b);
console.log(users.size);// 2
Even though a and b look identical, they’re different objects in memory, so both get stored.
If you want “unique by id”, store the id in a Set instead:
typeUser = {id:number;name:string };
const userIdSet =newSet<number>();
constuser1:User = {id:1,name:"Ava" };
constuser2:User = {id:1,name:"Ava (copy)" };
userIdSet.add(user1.id);
userIdSet.add(user2.id);
console.log(userIdSet.size);// 1
Using Sets for type-safe unions
A Set can help validate values against a known list.
Example: allowed themes:
typeTheme ="light" |"dark" |"system";
const allowedThemes =newSet<Theme>(["light","dark","system"]);
functionsetTheme(theme:string) {
if (!allowedThemes.has(themeasTheme)) {
console.log("Invalid theme");
return;
}
console.log(`Theme set to ${theme}`);
}
You still need a cast because theme is a string, but the Set acts like a simple gatekeeper.
Handy patterns you’ll reuse
1) Toggle values
functiontoggleItem(set:Set<string>,value:string) {
set.has(value) ? set.delete(value) : set.add(value);
}
2) Merge Sets
const a =newSet([1,2]);
const b =newSet([2,3]);
const merged =newSet([...a, ...b]);
console.log([...merged]);// [1, 2, 3]
3) Remove items using another Set
const allIds =newSet([1,2,3,4]);
const blockedIds =newSet([2,4]);
const allowedIds =newSet<number>();
for (const idof allIds) {
if (!blockedIds.has(id)) {
allowedIds.add(id);
}
}
console.log([...allowedIds]);// [1, 3]
Summary
A Set object stores values without duplicates and gives you fast membership checks through has(). In TypeScript, Sets are great for removing duplicates, tracking processed items, and managing selection states in UIs. Once you learn the core methods like add(), delete(), and size, you’ll start spotting Set-friendly problems everywhere.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot