I am currently in the process of developing a straightforward function to eliminate duplicates from an array using TypeScript.
While I acknowledge that there are numerous methods to accomplish this task, my main objective is to enhance my understanding of type operations, so I prefer a solution that aligns with my existing code.
My Approach:
- The function will accept an array of objects and the key of the object as arguments
- The array of objects will be transformed into a dictionary to retain only distinct entries
- An array will then be created based on the objects and returned
Functional JavaScript Example:
function removeDuplicates(arr, propName) {
const newArr = [];
const lookup = {};
for (let i in arr) {
lookup[arr[i][propName]] = arr[i];
}
for (let i in lookup) {
newArr.push(lookup[i]);
}
return newArr;
}
Typescript Implementation (encountering a type error)
I have been attempting to convert the function to Typescript but have hit a roadblock when it comes to defining types for the 'lookup' variable.
Below is my Typescript code snippet:
function removeDuplicates<T, K extends keyof T>(arr: T[], propName: K) {
const newArr: T[] = [];
const lookup: Partial<Record<T[K], T>> = {};
^^^^ the error arises here
for (let i in arr) {
lookup[arr[i][propName]] = arr[i];
}
for (let i in lookup) {
newArr.push(lookup[i]);
}
return newArr;
}
Error Message:
Type 'T[K]' does not meet the constraint 'string | number | symbol'
I comprehend the reason behind the error. The issue stems from the fact that the value associated with the object's key can potentially be anything. Nevertheless, for my specific scenario, I aim to restrict developers to only input keys whose values are either strings or numbers. Unfortunately, I am uncertain how to enforce this constraint in Typescript.