Open In App

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:

1. 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.

type uniqueArr = Set&lt;string&gt;;
const geeksSet: uniqueArr = 
    new Set([&quot;Array&quot;, &quot;String&quot;, &quot;Array&quot;]);
console.log([...geeksSet]); 

Output:

["Array", "String"] 

2. 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.

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

Output:

["Array", "String"] 

3. 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.

const uniqueArr: number[] = Array.from(
    new Map([1, 2, 3, 4, 5, 1, 2, 3, 6]
        .map((value) =&gt; [value, value])).values());
console.log(uniqueArr);

Output:

[1, 2, 3, 4, 5, 6] 

4. Using TypeScript Unique Type Feature

In this approach, we leverage TypeScript's unique type feature to create a type that ensures array elements are unique. This approach relies on mapped types and conditional types to achieve uniqueness.

Syntax:

type UniqueArray<T> = T extends ReadonlyArray<infer U> ? U[] & { __unique: never } : never;

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

type UniqueArray<T> = T extends ReadonlyArray<infer U> ? U[] & { __unique: never } : never;

function createUniqueArray<T>(arr: ReadonlyArray<T>): UniqueArray<T> {
    return Array.from(new Set(arr)) as UniqueArray<T>;
}

const uniqueNumbers: UniqueArray<number> = createUniqueArray([1, 2, 3, 3, 4, 5]);
const uniqueStrings: UniqueArray<string> = createUniqueArray(["apple", "banana", "apple"]);

console.log("Unique numbers:", uniqueNumbers);
console.log("Unique strings:", uniqueStrings);

Output:

"Unique numbers:",  [1, 2, 3, 4, 5] 
"Unique strings:", ["apple", "banana"]
Article Tags :