how to check if an element is in a set in typescript

To check if an element is in a Set in TypeScript, you can use the has method provided by the Set object. The has method returns a boolean value indicating whether an element is present in the set or not.

Here's an example:

index.ts
const mySet = new Set<string>();
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");

if (mySet.has("apple")) {
  console.log("Apple is in the set");
} else {
  console.log("Apple is not in the set");
}
213 chars
11 lines

In this example, we create a new Set object mySet and add some string elements to it. Then we use the has method to check if the element "apple" is present in the set or not. If it is present, we print "Apple is in the set", otherwise, we print "Apple is not in the set".

Note that the has method performs a strict equality check (===) to determine if an element is in the set. So, if you add a number like 5 to the set, you cannot check if the string "5" is in the set using has method.

gistlibby LogSnag