How to use TypeScript Unique Type Feature In Typescript
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"]
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