I have a helper function that removes duplicates from array
export const removeDublicatesFromArray = (
array: IRegulations[],
key: string
) => {
return [
...new Map(array.map((item: IRegulations) => [item[key], item])).values(),
]
}
And TS gives me an error on [item[key]
.
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'IRegulations'.
No index signature with a parameter of type 'string' was found on type 'IRegulations'
I did a research and fixed this error passing
Record<string, string>[]
instead of IRegulations[]
but it broke the code where this function is used.
Any way I can handle this error with these types?
CodePudding user response:
This will solve the issue
export const removeDublicatesFromArray = (
array: IRegulations[],
key: keyof IRegulations
) => {
return [
...new Map(array.map((item: IRegulations) => [item[key], item])).values(),
]
}
The problem you are seeing here is due to the type of key
being string. You see you are allowing the caller of removeDublicatesFromArray
to pass any string, that may not be a property of IRegulations
so, it may fails. The caller must ensure that they are passing the right key for it to work and hence you need to constraint the type of key
as keyof IRegulations
PS: I did not check the logic, I just fixed the type error and explained the thought process behind it.