How to Define Type for Array With Unique Items in TypeScript ?
Last Updated :
18 Jul, 2024
Defining a type for an array with unique items in TypeScript ensures that your data structures are robust and error-resistant. Here, we'll explore several methods to implement this functionality, each tailored to different use cases.
Below are the possible approaches:
1. Using Set
A Set in TypeScript is an ideal choice for ensuring all elements in a collection are unique. It naturally excludes duplicate entries.
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"]
2. Using Generics
Generics enhance flexibility and code reusability by enabling you to write a function or type that can work over a variety of types rather than a single one.
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"]
3. Using Map
A Map can be used to track unique keys, which is handy when you need to maintain unique elements derived from more complex data structures.
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]
4. Using TypeScript Unique Type Feature
TypeScript's advanced types can be used to enforce unique items in an array through type manipulation, ensuring compile-time checks for uniqueness.
Syntax:
type UniqueArray<T> = T extends ReadonlyArray<infer U> ? U[] & { __unique: never } : never;
Example: Below is the implementation of the above-discussed approach.
JavaScript
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"]