What is TypeScript Set?
A “TypeScript Set” is a data structure that lets you store unique values of any type, whether they are primitive values or object references.
It’s similar to the Set object in JavaScript but with the added benefits of TypeScript’s type system.
They’re used in many programming languages, not just TypeScript, to hold unique items.
To fully understand here are some important details you need to know:
Uniqueness:
Each element in a Set is unique. If you try to add a duplicate item, it won’t be added.
Methods:
Set comes with several methods like add(), delete(), and has() for adding, removing, and checking the presence of elements.
Iterability:
You can iterate over the elements of a Set in the order of insertion.
Creating Set
Here’s the syntax for creating and using a Set in TypeScript.
const subjects = new Set<string>();
What are the different Set Methods?
A Set object provides several methods that allow you to manipulate the collection of unique values.
Here are the different methods available for a Set:
Method | Description |
---|---|
set.add(value) | It is used to add a new element with the specified value to the Set. |
set.clear() | It is used to remove all elements from the Set. |
set.delete() | It is uses to delete or remove the specified element from the Set and returns a boolean indicating whether the element was successfully removed. |
set.has(value) | It returns a boolean indicating whether an element with the specified value exists in the Set. |
set.size() | It is use to determine the number of elements in the Set. |
TypeScript Set Example Using different methods
The set methods can be comprehended through the example provided below.
// Creating a Set to store unique subjects
const subjects = new Set<string>();
// Adding subjects to the Set
subjects.add('Mathematics');
subjects.add('Physics');
subjects.add('Chemistry');
subjects.add('Biology'); // This will be added as it's not a duplicate
// Checking if a subject is in the Set
console.log(subjects.has('Physics')); // Outputs: true
// Deleting a subject from the Set
subjects.delete('Biology');
// Checking the size of the Set
console.log(subjects.size); // Outputs the number of elements in the Set
// Iterating over the Set of subjects
for (let subject of subjects) {
console.log(subject);
}
// or using forEach
subjects.forEach((subject) => {
console.log(subject);
});
Output:
[LOG]: true
[LOG]: 3
[LOG]: "Mathematics"
[LOG]: "Programming"
[LOG]: "Software Development"
[LOG]: "Mathematics"
[LOG]: "Programming"
[LOG]: "Software Development"
What is Chaining of Set Method?
Chaining of set methods in TypeScript, often referred to as method chaining, is a pattern that allows multiple setter methods to be called in a single statement.
It’s achieved by having each setter method return the object itself (this), which allows the calls to be chained together. Here’s an example to illustrate:
class SubjectChain {
private _programming: number = 0;
private _webDevelopment: string = '';
setProgramming(score: number): SubjectChain {
this._programming = score;
return this; // Enables chaining by returning the object itself
}
setWebDevelopment(grade: string): SubjectChain {
this._webDevelopment = grade;
return this; // Enables chaining by returning the object itself
}
}
// Usage of chaining:
const studentGrades = new SubjectChain()
.setProgramming(98)
.setWebDevelopment('A+');
In this modified example, setProgramming and setWebDevelopment are the setter methods that allow you to set the scores for programming and webdevelopmentsubjects, respectively.
By returning this in each method, we enable the chaining of these methods for a fluent and streamlined way of setting multiple properties.
How to iterate Set Data?
To iterate over data in a Set
object in TypeScript, you can use several methods.
Here’s a simple example using the for…of loop, which is one of the most common ways to iterate through the elements of a Set
:
Absolutely! Here’s how you can iterate over a Set
object with a variable named subjects
:
let subjects = new Set(['Math', 'Science', 'Programming', 'English']);
for (let subject of subjects) {
console.log(subject);
}
This for…of loop will log each subject in the Set to the console.
Similarly, you can use the forEach method to perform an action for each element in the Set:
subjects.forEach((subject) => {
console.log(subject);
});
Both methods will iterate through the subjects set, allowing you to access and manipulate each subject as needed.
Conclusion
So that would be the end of our discussion about TypeScript’s Set, which is a data structure that ensures the uniqueness of its elements, providing a collection of non-duplicate values.
It comes with a suite of methods like add(), delete(), has(), and other methods mentioned above that help programmers to facilitate the management of its contents.
By understanding and implementing the void type as outlined in this article, you can write more predictable and type-safe code.
I hope this article has given you some insights and helped you understand the TypeScript set.
If you have any questions or inquiries, please don’t hesitate to leave a comment below.