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 sets
let 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 values
console.log(names.has("Theodore")) // true
console.log(evenNumbers.has(5)) // false
console.log(booleanValues.has(true)) // true
console.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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources