How to create a set in TypeScript

Overview

We use a set as a data structure to store distinct values. Sets are prevalent across different programming languages. It is different from arrays because it makes sure that there are no duplicates in the values assigned to it.

Syntax

new Set<type>()
Syntax for creating a Set in TypeScript

Parameters

  • type: This represents the data type that the set must contain.

Return value

A new set with distinct values is returned.

Example

// 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"])
// log the sets to the console
console.log(names)
console.log(evenNumbers)
console.log(booleanValues)
console.log(countries)

Explanation

  • Line 2–5: We create different sets, each with the particular data type we want.
  • Lines 8–11: We log the sets we created to the console.

Free Resources