Open In App

How to Define Type for Array With Unique Items in TypeScript ?

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

Using Set

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.

Javascript




type uniqueArr = Set<string>;
const geeksSet: uniqueArr =
    new Set(["Array", "String", "Array"]);
console.log([...geeksSet]);


Output:

["Array", "String"] 

Using Generics

In this approach, we have defined a generic type as “uniqueArr<T>“, which represents the array of type T with the property of __unique get unique items. We have defined the createArr function which uses the generic type to filter out the duplicate items from the array and a resArr is created with these string elements that contain only the unique array elements.

Syntax:

// generic type
type MyGenericType<T> = /* definition */;
// using a generic type in a function
function myGenericFunction<T>(param: T): /* implementation */ {
// ...
}

Example: Below is the implementation of the above-discussed approach.

Javascript




type uniqueArr<T> = T[] & { __unique: never };
function creatrArr<T>(arr: T[]): uniqueArr<T> {
    const uniqueArray = arr.filter((val, indx, self) =>
        self.indexOf(val) === indx);
    return uniqueArray as uniqueArr<T>;
}
const resArr: uniqueArr<string> =
    creatrArr(["Array", "String", "Array"]);
console.log(resArr);


Output:

["Array", "String"] 

Using Map

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.

Javascript




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] 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads