In Typescript, The Set is a built-in object that represents a collection of unique values.
It allows us to store and retrieve values, ensuring that each value in the set is unique.
We can create a new Set by using the Set constructor.
let stringSet = new Set<string>(); let numberSet = new Set<number>(); let customSet = new Set<{name: string, age: string}>();
`stringSet` creates an empty set that will store `string` values.
`numberSet` creates an empty set that will store `numeric` values.
`customSet` creates an empty set that will store `custom object with a name in string and age in number` values.
let stringSet = new Set<string>(); let numberSet = new Set<number>(); stringSet.add("Apple"); stringSet.add("Banana"); stringSet.add("Carrot"); stringSet.add("Dragon Fruit"); stringSet.add("Carrot"); // Ignored, as "Carrot" is already in the set numberSet.add(1); numberSet.add(2); numberSet.add(3); numberSet.add(4); numberSet.add(1); // Ignored, as 1 is already in the set
We can add elements to a Set using the add method.
let stringSet = new Set<string>(); let numberSet = new Set<number>(); stringSet.add("Apple"); stringSet.add("Banana"); stringSet.add("Carrot"); stringSet.add("Dragon Fruit"); numberSet.add(1); numberSet.add(2); numberSet.add(3); numberSet.add(4); console.log(stringSet.size); // Output: 4 console.log(numberSet.size); // Output: 4
let stringSet = new Set<string>(); let numberSet = new Set<number>(); stringSet.add("Dragon Fruit"); numberSet.add(4); console.log(stringSet.has("Dragon Fruit")); // Output: true console.log(stringSet.has("Orange")); // Output: false console.log(numberSet.has(4)); // Output: true console.log(numberSet.has(6)); // Output: false
We can get the number of elements in a set using the size property.
stringSet.delete("Banana"); // Removes the element with value Banana numberSet.delete(4); // Removes the element with value 4
stringSet.clear(); // Removes all elements from the set numberSet.clear(); // Removes all elements from the set
We can check if a specific value is present in the set using the has method.
let mixedValuesSet = new Set<any>(); mixedValuesSet.add(20); mixedValuesSet.add("Apple"); mixedValuesSet.add(true);
let arrayFromStringSet = [...stringSet]; let arrayFromNumberSet = [...numberSet];
We can remove elements from a set using the delete method.
stringSet.forEach(value => { console.log(value); }); numberSet.forEach(value => { console.log(value); });
We can remove all elements from a set using the clear method.
A Set can store values of different types.
We can convert a set to an array using the spread operator.
We can iterate over the elements of a set using the forEach method.