How to Convert Set to Array in TypeScript

To convert a Set to Array in TypeScript, you can “use the Array.from() function or Spread operator”.

Method 1: Using Array.from()

The Array.from() method creates a new array instance from an iterable object. Since a Set is iterable, it can be directly passed to Array.from() to create an array.

let mainSet = new Set<string>();

mainSet.add("apple");
mainSet.add("banana");
mainSet.add("cherry");

let mainArray = Array.from(mainSet);
console.log(mainArray)

Output

Set to Array in TypeScript

Additionally, if you want to perform some operations on each item of the Set while converting, you can provide a map function to Array.from():

let squaredArray = Array.from(mainSet, value => value * value);

Method 2: Using the spread operator

The spread operator (…) is a concise way to expand elements of iterable objects (like arrays, strings, and sets) into individual elements.

When converting a Set to an array in TypeScript (or JavaScript), you can use the spread operator inside array literals to spread the set into an array.

let mainSet = new Set();

mainSet.add("apple");
mainSet.add("banana");
mainSet.add("cherry");

let mainArray = [...mainSet];
console.log(mainArray)

Output

[ 'apple', 'banana', 'cherry' ]

That’s it!

Related posts

TypeScript Enum to Array

TypeScript Enum to String

TypeScript String to Number

TypeScript String to Enum

TypeScript String to Boolean

Leave a Comment