简体   繁体   中英

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.

Any way I can handle this error with these types?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM