To check if a specific item is present in a Set in TypeScript, you can use the has
method.
In this example,
mySet
containing elements of a specific type.has
method of the Set to check if a specific item is present.has
method returns true
if the item is present in the Set, otherwise it returns false
.// Define Set with items
const mySet: Set<string> = new Set(["apple", "banana", "orange", "grape", "melon"]);
// Check if item is present
const item: string = "banana";
const isPresent: boolean = mySet.has(item);
// Print result
console.log(`Is ${item} present in the Set? ${isPresent}`);
Is banana present in the Set? true
In this example,
mySet
containing elements of a specific type.has
method of the Set to check if a specific item is not present.has
method returns false
if the item is not present in the Set.// Define Set with items
const mySet: Set<string> = new Set(["apple", "banana", "orange", "grape", "melon"]);
// Check if item is not present
const item: string = "peach";
const isNotPresent: boolean = !mySet.has(item);
// Print result
console.log(`Is ${item} not present in the Set? ${isNotPresent}`);
Is peach not present in the Set? true
In this tutorial, we learned How to check if a Specific Item is present in the Set in TypeScript language with well detailed examples.