How to use Set In Typescript
In this approach, we have a TypeScript type named uniqueArr which is defined as ‘Set<string>‘. This ensures that any variable of this type will represent an array structure with unique string elements. The geekSet creates an array and logs its unique element using the spread operator.
Syntax:
const mySet: Set<string> = new Set(["element1", "element2", "element3"]);
Example: Below is the implementation of the above-discussed approach.
type uniqueArr = Set<string>;
const geeksSet: uniqueArr =
new Set(["Array", "String", "Array"]);
console.log([...geeksSet]);
Output:
["Array", "String"]
How to Define Type for Array With Unique Items in TypeScript ?
In this article, we will learn how we can define a type for an array with unique items in TypeScript.
Below are the possible approaches:
Table of Content
- Using Set
- Using Generics
- Using Map
- Using TypeScript’s Unique Type Feature