top of page

TypeScript Set and TypeScript Weakset

TypeScript provides two powerful collection classes called Set and WeakSet, which allow you to work with unique sets of values in your code. Sets are similar to maps, but they store only keys without associated values, while WeakSets specifically hold objects and provide automatic garbage collection for unreferenced objects.

TypeScript Set and TypeScript WeakSet

In this article, we will explore the features, properties, and methods of TypeScript Sets and WeakSets. We'll learn their usage, understand how they differ from each other and from other collection classes, and provide practical examples to illustrate their functionalities.



Table of Content:

  • What is TypeScript Set?

1. How to create TypeScript Set

2. TypeScript Set Properties and Methods

3. Union, Intersection, and Difference Operations in TypeScript Sets

4. Iterate over a TypeScript Set

5. Advantages of TypeScript Set

6. Disadvantages of TypeScript Set

  • What is TypeScript Weakset?

1. How to create TypeScript WeakSet

2. TypeScript Weakset Properties and methods

3. Advantages of TypeScript WeakSet

4. Disadvantages of TypeScript WeakSet

  • Difference: TypeScript Set vs TypeScript WeakSet

  • Conclusion


What is TypeScript Set?

In TypeScript, a Set is a collection that is similar to maps, but it only stores unique keys and does not store key-value pairs. The Set object allows you to store unique values of any type, including primitive values or object references. Sets are collections of values, and you can iterate over their elements in the order of insertion.


One important characteristic of Sets is that a value can only occur once within the Set's collection. Each value is unique, and duplicate values are automatically removed.


Sets are useful when you need to maintain a collection of unique elements or when you want to quickly check if a value already exists in a collection without worrying about duplicates.


TypeScript Sets:

  • Sets store unique values, similar to maps but without key-value pairs.

  • They can store values of any type, including primitives and object references.

  • Sets maintain the insertion order of elements, allowing you to iterate over them in that order.

  • Each value can only occur once within the Set's collection.


How to Create TypeScript Set

To create a TypeScript Set, you can use the new keyword as shown below:

var set = new Set();

You can also initialize a TypeScript Set with an array of values:

var map = new Map([
     [ "apple" ],
     [ "banana" ],
     [ "carraot"]
 ]);

TypeScript Set Properties and Methods

The TypeScript Set provides various properties and methods that you can use:


1. Adding entries to a TypeScript Set:

You can add entries to a Set using the add method:

let country = new Set();
set.add('India');
set.add('Aus');
set.add('England');

Alternatively, you can chain the add method to add entries to a TypeScript Set in a more concise manner:

let country = new Set().add('India').add('Aus').add('England');

2. Checking if a key is present in a TypeScript Set:

You can use the has method to check if a key is present in a Set:

country.has("Aus");//true

3. Deleting a value from a TypeScript Set:

You can remove a value from a Set using the delete method:

country.delete('Aus');

4. Counting the number of entries in a TypeScript Set:

To determine the number of entries in a Set, you can access the size property:

country.size; //2

5. Emptying the entire TypeScript Set:

You can clear all entries in a Set using the clear method:

country.clear();

Since Sets can only store unique values, adding a value that already exists has no effect.


Here's an example that demonstrates the usage of a TypeScript Set:

let country = new Set();
country.add('India');
country.size
// 1
country.add('India');
country.size
// 1

In this example, even though the value 'India' is added twice, the Set still contains only one unique entry.


Comparing TypeScript Set elements

In TypeScript Sets, elements are compared using the === operator, which checks for strict equality. However, there is an exception when it comes to comparing "NaN" values. In Sets, "NaN" is considered like any other value and is not treated as a special case.


Example:

let set = newSet(); 
set.add(NaN); 
console.log(set.size); // Output: 1
console.log(set.has(NaN)); // Output: true

In this example, we create a new Set called set and add a single element, NaN, using the add() method. We then check the size of the Set, which returns 1 because it contains one unique element. Subsequently, we use the has() method to check if NaN is present in the Set, and it returns true.


Comparing Objects in TypeScript Sets:

Similar to the behavior of the === operator, two different objects are never considered equal in TypeScript Sets. Each object is treated as a separate entry, even if they have the same properties or values.

Example:


Example:

let set = newSet(); 
set.add({}); 
console.log(set.size); // Output: 1 
set.add({}); 
console.log(set.size); // Output: 2

In this example, we create a new Set called set and add an empty object using the add() method. Checking the size of the Set returns 1 because it contains one unique object. However, when we add another empty object to the Set, the size increases to 2. This is because each object is considered distinct, regardless of their internal properties or values.


Adding Duplicate Elements to TypeScript Sets:

Adding an element a second time to a TypeScript Set has no effect. Sets can only store unique values, so duplicate entries are automatically discarded.


Example:

let set = newSet(); 
set.add("hi"); 
console.log(set.size); // Output: 1 
set.add("hi"); 
console.log(set.size); // Output: 1

In this example, we create a new Set called set and add the string "hi" using the add() method. The initial size of the Set is 1 because it contains one unique element. However, when we attempt to add "hi" again, the size remains 1. This is because the Set recognizes that "hi" is already present and ignores the duplicate entry.


TypeScript Sets follow the behavior of strict equality (===) for element comparison, except for the special case of "NaN." Additionally, duplicate elements are automatically discarded when added multiple times to a Set.


Union, Intersection, and Difference Operations in TypeScript Sets

ECMAScript 6 Sets have no methods for computing the union (e.g. addAll), intersection (e.g. retainAll) or difference (e.g. removeAll). This section explains how to work around that limitation.


1. Union (a ∪ b):

To create a Set that contains the elements of both Set a and Set b, you can use the spread operator (...) to merge the two Sets.


Example:

let a = new Set([10, 20, 30, 40]); 
let b = new Set([40, 30, 20]); 
let union = new Set([...a, ...b]); 
console.log(union); 
// Output: Set { 10, 20, 30, 40 } 

In this example, Set a contains elements [10, 20, 30, 40], and Set b contains elements [40, 30, 20]. By spreading the elements of both Sets using ..., we create a new Set called union that contains all the unique elements from both Sets.


2. Intersection (a ∩ b):

To create a Set that contains the elements common to Set a and Set b, you can use the filter() method along with the has() method to check for the presence of each element in the other Set.


Example:

let a = new Set([10, 20, 30, 40]); 
let b = new  Set([40, 30, 20]); 
let intersection = newSet([...a].filter(x => b.has(x))); 
console.log(intersection); 
// Output: Set { 20, 30, 40 }

In this example, Set a contains elements [10, 20, 30, 40], and Set b contains elements [40, 30, 20]. Using the spread operator (...), we convert Set a to an array and filter out only those elements that are present in Set b. The resulting array is used to create a new Set called intersection, which contains the common elements.


3. Difference (a \ b):

To create a Set that contains the elements from Set a that are not present in Set b, you can use the filter() method along with the has() method to check for the absence of each element in Set b.


Example:

let a = new Set([10, 20, 30, 40]); 
let b = new Set([40, 30, 20]); 
let difference = new Set([...a].filter(x => !b.has(x))); 
console.log(difference); 
// Output: Set { 10 } 

In this example, Set a contains elements [10, 20, 30, 40], and Set b contains elements [40, 30, 20]. By converting Set a to an array using the spread operator (...), we filter out the elements that are present in Set b using the has() method. The resulting array is used to create a new Set called difference, which contains the elements from Set a that are not present in Set b. In this case, the element 10 is the only one that satisfies the condition.


Iterate over a TypeScript Set


1. Using the for-of Loop

You can iterate over the elements of a TypeScript Set using the for-of loop. Each iteration will provide you with the current element from the Set.


Example

let numbers = new Set([1, 2, 3, 4, 5]); 
for (letnumberof numbers) 
{     
    console.log(number); 
} 

// Output:
// 1
// 2
// 3
// 4
// 5

Another Example

let set = new Set(); 
set.add("apple"); 
set.add("banana"); 
set.add("cherry"); 
for (let fruit of set) 
{   
    console.log(fruit); 
} 

// Output:
// apple
// banana
// cherry

2. Using the forEach Loop

You can also use the forEach loop to iterate over the elements of a TypeScript Set. The forEach loop takes a callback function as a parameter, which is executed for each element in the Set.


Example:

let colors = new Set(["red", "green", "blue"]); 
colors.forEach(function(color) 
{   
    console.log(color); 
}); 

// Output:
// red
// green
// blue


Advantages of TypeScript Set

  1. It automatically removes duplicate values, ensuring each value occurs only once within the collection

  2. It can store values of any type.

  3. It supports efficient iteration over their elements, allowing you to process each value in the insertion order.

  4. Checking for the presence of a value in a set is highly optimized, making it faster than searching in arrays or objects.

  5. It focuses on storing individual values, making them suitable for scenarios where you only need to track unique elements.

Disadvantages of TypeScript Set

  1. It does not provide direct key-value pairing like maps, so if you require associating data with each value, a set may not be the best choice.

  2. It maintains the insertion order of elements, which may not align with specific sorting requirements.

  3. It does not support direct indexing or random access to elements, so retrieving a specific value by its position is not possible.

  4. While Sets are widely supported in modern JavaScript environments, older browsers may have limited or no support.


What is TypeScript WeakSet?

TypeScript WeakSet is a collection that holds unique objects. It is similar to a Set, but it can only contain objects and nothing else. The main feature of a WeakSet is that if an object stored in it has no other reference variables, it will automatically be deleted or garbage collected.


The WeakSet object in TypeScript allows you to store weakly held objects in a collection. It is specifically designed to hold objects and provides the following characteristics:

  1. WeakSets only store objects, and not arbitrary values of any type like Sets.

  2. The objects stored in a WeakSet are held weakly, meaning that if there are no other references to an object stored in the WeakSet, it can be garbage collected.

  3. WeakSets do not have a list of current objects stored in the collection and are not enumerable.

Syntax:

var myWeakSet = new WeakSet([iterable with only objects]);

Example:

var objWeakSet = new WeakSet([{ text: "hi" }]); 
var obj1 = { text: "hello" }; 
var obj2 = { text: "bye" };  

objWeakSet.add(obj1); 
console.log(objWeakSet.has(obj1)); 
console.log(objWeakSet.has(obj2)); 
objWeakSet.add(obj2); 
console.log(objWeakSet.has(obj2));

In this example, we create a WeakSet called objWeakSet and initialize it with an iterable containing a single object { text: "hi" }. We also create two additional objects obj1 and obj2. We then add obj1 to the WeakSet using the add() method and check if it exists in the WeakSet using the has() method. The first console.log statement returns true because obj1 is present in the WeakSet. However, when checking for obj2, which was not added to the WeakSet initially, it returns false. Finally, we add obj2 to the WeakSet and check its presence again, which returns true.


The WeakSet in TypeScript provides a way to store weakly held objects, where the garbage collector can automatically remove objects that are no longer referenced, making it useful in scenarios where you want to associate additional data or metadata with objects without keeping them alive artificially.


TypeScript WeakSet Properties and Methods

TypeScript WeakSet is similar to Set, but it can only store objects (not primitives). Objects exist in a WeakSet as long as they are reachable from somewhere else. Like Set, WeakSet supports the following methods:

  1. add(value: T): Appends a new object with the given value to the WeakSet object.

  2. has(value: T): Returns a boolean indicating whether an element with the given value is present in the WeakSet object or not.

  3. delete(value: T): Removes the element associated with the value. After deletion, WeakSet.prototype.has(value) will return false.


Example:

class Book 
{   
    constructor(public title: string) {} 
}  

let weakSet = new WeakSet();  // Create book objects
let book1 = new Book("The Catcher in the Rye"); 
let book2 = new Book("To Kill a Mockingbird"); 
let book3 = new Book("Pride and Prejudice");  

// Add book objects to the WeakSet 
weakSet.add(book1); 
weakSet.add(book2);  

// Check if book objects exist in the WeakSet
console.log(weakSet.has(book1)); // Output: true
console.log(weakSet.has(book2)); // Output: true
console.log(weakSet.has(book3)); // Output: false

// Remove a book object from the WeakSet 
weakSet.delete(book2);  

// Check if book objects exist after deletion
console.log(weakSet.has(book1)); // Output: true
console.log(weakSet.has(book2)); // Output: false
console.log(weakSet.has(book3)); // Output: false

In this, we create a class called Book with a title property. We then create three instances of Book objects: book1, book2, and book3. We add book1 and book2 to the WeakSet using the add() method. We use the has() method to check if the book objects exist in the WeakSet.


Important to note that WeakSets do not support properties like size, methods like clear(), or operations like iterating over the elements using keys or iterations. WeakSets are designed to allow automatic garbage collection of objects that are no longer reachable, and they focus on simplicity and efficiency when managing object references.


Advantages of TypeScript WeakSet

  1. WeakSets are specifically designed to hold object references, providing a convenient way to manage object collections.

  2. It supports automatic garbage collection, meaning that if an object stored in the WeakSet has no other references, it can be removed from memory.

  3. It can help prevent memory leaks by automatically removing unreferenced objects, reducing the risk of retaining unnecessary memory.

  4. It does not expose the objects stored within them, making it useful in scenarios where privacy or encapsulation is required.

Disadvantages of TypeScript WeakSet

  1. WeakSets can only store objects as values and cannot hold primitive values or other data types.

  2. It does not support direct iteration over their elements, making it more challenging to perform operations on the stored objects.

  3. It does not have a built-in size property, so determining the number of objects stored in a WeakSet requires additional logic.

  4. Similar to Sets, WeakSets may not be fully supported in older JavaScript environments, so compatibility with legacy browsers should be considered.


Difference: TypeScript Set vs TypeScript WeakSet

Features

JavaScript Set

JavaScript WeakSet

Types of Elements

Can store any type of values

Can only store objects as values

Uniqueness of Values

Stores unique values

Stores weakly held unique objects

Garbage Collection

Not affected by garbage collection

It supports automatic garbage collection

Size

Has a "Size" property

Does not have "Size" property

Iteration

Supports iteration over elements

Does not support iteration

Keys and values

Stores only keys

N/A

Use Cases

General purpose collections

Storing object references


Conclusion

When choosing between JavaScript Set and WeakSet, it's essential to consider your specific requirements. Sets are suitable for general-purpose collections of unique values, while WeakSets are useful when managing object references and automatic garbage collection is desirable.

Recent Posts

See All

Kommentare


bottom of page