0

I have a method in my component which is strictly used for removing duplicate values from an array.

const removeDuplicateScenarios = (scenariosList: Scenario[]): Scenario[] => {
  return _.filter(scenariosList, el => _.filter(scenariosList, e => e.id === el.id).length === 1);
};

However, I want to completely make this reusable as possible wherein I dont define the types explicitly but does the job.

const removeDuplicateValues = (values: []): [] => {
  return _.filter(values, el => _.filter(values, e => e.id === el.id).length === 1);
};

Is any the only type I can use over here?

However, I get these errors:

TS2322: Type 'never[]' is not assignable to type '[]'.   
Types of property 'length' are incompatible.
Type 'number' is not assignable to type '0'.

Please advice.

1 Answer 1

1

Can you use a generic? Docs at https://www.typescriptlang.org/docs/handbook/generics.html

example code. Lots more info in the typescript docs.

function removeDuplicateValues<T>(values: T[]): T[] => {
  return _.filter(values, el => _.filter(values, e => e.id === el.id).length === 1);
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Did as const removeDuplicateValues = <T extends { id: number }>(values: T[]): T[] => { return filter(values, el => filter(values, e => e.id === el.id).length === 1); };

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.