Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

typescript

How to create a set in TypeScript

Theodore Kelechukwu Onyejiaku

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)
Create a Set in TypeScript

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.

RELATED TAGS

typescript

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring