0

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?

1
  • Please provide a minimal reproducible example that clearly demonstrates the issue you are facing. Ideally someone could drop the code into a standalone IDE like The TypeScript Playground (link here!) and immediately get to work solving the problem without first needing to re-create it. So there should be no typos, unrelated errors, or undeclared types or values. Also, when you say "broke the code where this function is used" you should include enough of that code to show others what you mean. Commented Nov 18, 2021 at 17:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.