Understanding TypeScript Sets

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.

Creating and Adding Elements in a Set with TypeScript Generics

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.

Removing Elements from a Set

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.

Checking a Set's Size and Membership

We examine the size of a Set or its total entries using the size attribute. The .has() method checks whether an element is present in the Set.

In this script, our universe comprises four elements — two planets (Planet and Moon), one asteroid, and one star. Consequently, the size is 4. The .has() method finds 'Star' but does not locate 'Galaxy'.

Lesson Summary and Practice

Bravo, Explorer! You now understand Sets in TypeScript. We have covered the creation of Sets, the insertion and removal of elements, and how to check a Set's size and membership.

Now, apply your newly acquired skills in coding challenges to reinforce what you have learned. Are you ready to invoke your inner explorer? Go for it!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal