How to use Map In Typescript
In this approach, we are using the Map to maintain the unique values of an array. The resulting array (uniqueArr) is generated by converting the keys of the map to an array using Array.from. Then the TypeScript type for uniqueArr is explicitly declared as the number[] to consist of unique numeric elements.
Syntax:
const myMap = new Map<KeyType, ValueType>();
Example: Below is the implementation of the above-discussed approach.
const uniqueArr: number[] = Array.from(
new Map([1, 2, 3, 4, 5, 1, 2, 3, 6]
.map((value) => [value, value])).values());
console.log(uniqueArr);
Output:
[1, 2, 3, 4, 5, 6]
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
Contact Us