TypeScript Tutorial
TypeScript Set
Set stores unique values. Add, has, and iterate without duplicates.
Unique values
A Set is a collection that refuses duplicates. Think of it as a Map with only keys: membership, not a payload. The type is Set<number> or Set<string>. Construct with new Set<number>().
Use it when the question is “have I already seen this?” or “give me these values once each.” An array can hold the same number twice. A set will not. C++ set also unique-ifies; it also sorts. JavaScript’sSet keeps insertion order and does not sort.
add and size
add inserts a value when it is new. size is how many unique values you have. After two different adds, size is 2.
Example
const seen = new Set<number>();
seen.add(4);
seen.add(1);
console.log(seen.size);Output is 2.
Click Try it in TypeScript under the example. That opens /typescript/try. This is not the C++ editor at /cpp/try.
Duplicates are ignored
Add the same value again and the set stays the same. There is no error and no extra element. That silence is the feature: you can add every number you see in a stream and end with the distinct ones.
Example
const seen = new Set<number>();
seen.add(4);
seen.add(1);
seen.add(4);
seen.add(1);
seen.add(4);
console.log(seen.size);
console.log([...seen].join(" "));Output is 2 on the first line, then 4 1. Five adds, two values, printed in insertion order — not sorted order. Spread ([...seen]) copies the set into an array sojoin works.
has
has(value) returns true if the value is in the set and false if it is not. Use it as a yes-or-no test before you rely on the value being there.
Example
const allowed = new Set<number>();
allowed.add(200);
allowed.add(201);
allowed.add(204);
console.log(allowed.has(200));
console.log(allowed.has(404));Output is true then false. Status 200 is allowed. 404 is not in the set.
Iterate
for...of walks the set in insertion order. For string that is not lexicographic unless you happened to add them that way. There is no index; you do not write seen[0].
Example
const tags = new Set<string>();
tags.add("stl");
tags.add("map");
tags.add("set");
tags.add("map");
console.log(tags.size);
for (const tag of tags) {
console.log(tag);
}Size is 3 because the second "map" was ignored. The loop prints stl, thenmap, then set.
Set versus array
| number[] | Set<number> | |
|---|---|---|
| Duplicates | Allowed | Silently ignored |
| Order in a loop | Insertion order | Insertion order |
| Lookup | Index, or scan | has by value |
Index [i] | Yes | No |
Keep an array when position matters or when the same value may appear twice on purpose. Switch to a set when uniqueness is the rule you want the type to enforce.
What comes after Set
You now have arrays, Map, and Set. The next chapter stays on arrays and looks at algorithms: sort, find, filter, and reduce, with typed callbacks.