DEV Community

Dominik Nieuważny
Dominik Nieuważny

Posted on • Originally published at stateoftype.dev

New Set Methods in TypeScript 5.5

TypeScript 5.5 introduces support for new ECMAScript methods on the Set object: union, intersection, difference, and symmetricDifference. These methods allow for more intuitive and readable operations on sets.

🔍 What Are Sets?
In JavaScript, a Set is a collection of unique values. Unlike arrays, sets automatically eliminate duplicate entries.

🆕 New Methods Explained

union

Combines elements from both sets, removing duplicates

  const setA = new Set([1, 2]);
  const setB = new Set([2, 3]);
  const unionSet = setA.union(setB); // Set {1, 2, 3}
Enter fullscreen mode Exit fullscreen mode

intersection

Returns elements common to both sets.

  const setA = new Set([1, 2]);
  const setB = new Set([2, 3]);
  const intersectionSet = setA.intersection(setB); // Set {2}
Enter fullscreen mode Exit fullscreen mode

difference

Returns elements present in the first set but not in the second.

  const setA = new Set([1, 2]);
  const setB = new Set([2, 3]);
  const differenceSet = setA.difference(setB); // Set {1}
Enter fullscreen mode Exit fullscreen mode

symmetricDifference

Returns elements present in either set, but not in both.

  const setA = new Set([1, 2]);
  const setB = new Set([2, 3]);
  const symmetricDiffSet = setA.symmetricDifference(setB); // Set {1, 3}
Enter fullscreen mode Exit fullscreen mode

⚙️ How to Enable These Methods

To use these methods, ensure your tsconfig.json includes the following settings:

{
  "compilerOptions": {
    "target": "ESNext",
    "lib": ["ESNext"]
  }
}
Enter fullscreen mode Exit fullscreen mode

This configuration allows TypeScript to recognize and compile code using these new Set methods.

These enhancements make set operations more straightforward and align JavaScript more closely with set operations found in other programming languages.

Top comments (0)