TypeScript Set Basic Usage and Features
In TypeScript, a Set is a collection type used to store unique values. The values within a Set are ordered by the sequence in which they were added, and each value must be unique.
The syntax for defining a Set is as follows:
let mySet = new Set<number>();
Here, mySet is an empty Set, capable of storing only values of the number type. You can also specify initial values when creating a Set, such as:
let mySet = new Set<number>([1, 2, 3, 4, 5]);
In this case, mySet contains five numbers ranging from 1 to 5.
The Set object provides a series of methods for operations such as adding, deleting, and searching for elements. For example, you can use the add() method to add new elements to a Set, the delete() method to remove elements, and the has() method to check if an element exists within the Set. Here is an example:
let mySet = new Set<number>();
mySet.add(1); // Add element 1 to the Set
mySet.add(2); // Add element 2 to the Set
mySet.add(3); // Add element 3 to the Set
mySet.delete(2); // Remove element 2 from the Set
console.log(mySet.has(1)); // Outputs: true
console.log(mySet.has(2)); // Outputs: false
The Set object can also use the forEach() method to iterate through elements in the collection. For example:
let mySet = new Set<number>([1, 2, 3]);
mySet.forEach(function(value) {
console.log(value);
});
// Outputs:
// 1
// 2
// 3
It is important to note that elements within a Set must be unique; therefore, if duplicate elements are added, only one instance will remain. Additionally, there is no specific order defined for elements in a Set, so they cannot be accessed using indices. If you need to access elements of a Set in a particular order, convert the Set into an array and then perform operations on it.