Let's initiate our journey with Sets. In TypeScript, a Set is a unique type of object that stores diverse data types, be they primitive or object variables. A Set does not contain duplicates. Imagine a Set as a special bag holding unique treasures (elements), ensuring that each remains exclusive.
The array houses duplicates, whereas the set displays only unique values.
In TypeScript, the creation of a Set leverages the new keyword alongside the Set() constructor. A distinctive feature of using Set in TypeScript is the ability to specify the type of elements it holds through generics. This is done by adding <type> next to Set, where type is the data type of the elements. This practice ensures type safety, allowing only elements of the specified type to be added to the Set.
In the example above, <string> is a generic type parameter that specifies the type of elements the Set will contain. This means universe is a Set that can only contain string elements, ensuring type safety at compile-time.
To add elements to the Set, use the .add() method. Each element added to the Set is checked for uniqueness; duplicates are not allowed, ensuring each element is unique within the Set.
In this example, although 'Star' is attempted to be added twice, the Set maintains it as a single entry, showcasing its inherent characteristic to prevent duplication. This behavior makes Set particularly useful for cases where the uniqueness of elements is a priority.
To eliminate entries from a Set, use the .delete() method. If you wish to clear a Set completely, apply the .clear() method.
The script above first eradicates Star from our Universe. Subsequently, the .clear() method entirely empties the Set, leaving it devoid of content.
