Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript Error: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type X

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any way I can handle this error with these types?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading