What is set.has() method in TypeScript?
Overview
In TypeScript, we can use the has() method of a set to check if the set contains the specified entry. Sets are used to store unique values that have no duplicates.
Syntax
set.has(value)
Syntax for the has() method of a Set in Typescript
Parameters
set: This is the set we want to check if it contains the specified value.
value: This is the value that we want to check if it exists.
Return value
If the set contains the specified value, then a true is returned. Otherwise, false is returned.
Code example
Let's look at the code below:
// create some setslet names = new Set<string>(["Theodore", "David", "John", "Janme"])let evenNumbers = new Set<number>([2, 4, 6, 8, 10, 12])let booleanValues = new Set<boolean>([true, false])let countries = new Set<string>(["Nigeria", "Brazil", "Ghana", "Egypt", "Germany"])// check if they contain some valuesconsole.log(names.has("Theodore")) // trueconsole.log(evenNumbers.has(5)) // falseconsole.log(booleanValues.has(true)) // trueconsole.log(countries.has("Tokyo")) // false
Code explanation
- Lines 2 to 5: We create some sets in TypeScript.
- Lines 9 to 12: We use the
has()method to check if some entries are contained in the sets we created. Then we print the results to the console.