This guide will explore the use of sets in TypeScript, including their properties, methods, and how to integrate them into TypeScript projects effectively.
What is a Set in TypeScript?
In TypeScript, a Set
is a collection of unique values that does not allow duplicate elements. A set is implemented with the Set
object, which is part of the ECMAScript 2015 (ES6) specification and fully supported in TypeScript.
Creating and initializing Sets
To create a set in TypeScript, you simply instantiate a new Set
object. You can initialize a set with or without values.
Example:
let mySet = new Set<number>() // an empty set of numberslet stringSet = new Set<string>(['apple', 'banana', 'cherry']) // set initialized with strings
Basic operations on Sets
Adding items
To add items to a set, use the add
method. This method appends a new element to a set, only if it is not already present in the collection.
mySet.add(1)mySet.add(2)mySet.add(1) // this will no-opp, and not add '1' again, as it is a duplicate
Checking for existence
To check if an item exists in a set, use the has
method.
console.log(mySet.has(1)) // trueconsole.log(mySet.has(3)) // false
has
will return true
if the element exists in the set, and return false
if the element does not exist in the set.
Removing items
To remove an item, use the delete
method.
mySet.delete(2) // removes '2' from the set
Clearing all items
To remove all items from a set, use the clear
method.
mySet.clear() // empties the entire set
Converting a set to an array
Sometimes, you might need to convert a set back into an array. You can do this using the spread operator ...
or Array.from
.
With the spread operator:
let arrayFromSet = [...stringSet]console.log(arrayFromSet) // ['apple', 'banana', 'cherry']
With Array.from
:
let arrayFromSet2 = Array.from(stringSet)console.log(arrayFromSet2) // ['apple', 'banana', 'cherry']
Both the spread operator ...
and the Array.from()
method functionally perform the same, however:
Array.from()
has additional capabilities: it can accept a map function as a second argument, allowing you to transform elements during the conversion process. For example:Terminallet arrayFromSet2 = Array.from(stringSet, (value) => value.toUpperCase())console.log(arrayFromSet2) // ['APPLE', 'BANANA', 'CHERRY']- The spread operator does not directly support transformation during unpacking; any transformation would require a separate operation like
map()
:Terminallet arrayFromSet = [...stringSet].map((value) => value.toUpperCase())console.log(arrayFromSet) // ['APPLE', 'BANANA', 'CHERRY']
Advanced set operations
Iterating over a set
You can iterate over the elements of a set using forEach
or a for...of
loop.
Example with forEach
:
stringSet.forEach((value) => {console.log(value)})
Example with for...of
loop:
for (let value of stringSet) {console.log(value)}
For further reading on the differences between these two loops, see the official TypeScript documentation.
Intersection, union, and difference of sets
To perform more complex operations like intersections, unions, and differences, you will need to implement helper functions:
Intersection:
function intersectSets<T>(setA: Set<T>, setB: Set<T>): Set<T> {let intersection = new Set<T>()for (let elem of setB) {if (setA.has(elem)) {intersection.add(elem)}}return intersection}
- The
intersectSets
function takes two sets,setA
andsetB
, and returns a new set that includes only the elements that are present in bothsetA
andsetB
. - It iterates through
setB
, checking if each element is present insetA
. If it is, the element is added to the intersection set.
Union:
function unionSets<T>(setA: Set<T>, setB: Set<T>): Set<T> {let union = new Set(setA)for (let elem of setB) {union.add(elem)}return union}
- The
unionSets
function also takes two sets,setA
andsetB
, and returns a new set containing all elements from bothsetA
andsetB
. - It initializes a new set
union
with the elements ofsetA
and then adds elements fromsetB
to this set. Since aSet
in JavaScript automatically handles duplicates (i.e., it does not add a duplicate element), this function will correctly contain all unique elements from both sets.
Difference:
function differenceSets<T>(setA: Set<T>, setB: Set<T>): Set<T> {let difference = new Set(setA)for (let elem of setB) {difference.delete(elem)}return difference}
- The
differenceSets
function computes the difference between two sets,setA
andsetB
, returning a new set containing elements that are insetA
but not insetB
. - It initializes a new set
difference
with the elements ofsetA
and then removes elements found insetB
.
For more information on the TypeScript Set
object, see the official TypeScript documentation.