What is the set.add() method in TypeScript?

Overview

A set is a data structure that stores data that is unique and without duplicates. We use the add() method to add a value to a set.

Syntax

theSet.add(value)
// Or chain the add() method
theSet.add(value1).add(value2).add(valueN)
Add a value to a set in Typescript

Note: This method can be chained as shown in the syntax above.

Parameters

theSet: This is the set to which we want to add values.

value1, value2, and valueN: These are the values we want to add to the set.

Return value

The value returned is a new set with the value added to it.

Example

// create some set instances
let names = new Set<string>()
let evenNumbers = new Set<number>()
let countries = new Set<string>()
let isMarried = new Set<boolean>()
// add values to the sets
names.add("Theodore")
names.add("Celeste")
names.add("Dave")
evenNumbers.add(2).add(4).add(8).add(10)
countries.add("Nigeria").add("Puerto Rico").add("Chile").add("India")
isMarried.add(true)
isMarried.add(false)
// log out all the sets
console.log(names)
console.log(evenNumbers)
console.log(countries)
console.log(isMarried)

Explanation

  • Lines 2–5: We create some sets.
  • Lines 8–16: We use the add() method to add values to the sets.
  • Lines 19–22: We print the sets to the console.