Home > Software engineering >  Typescript arrow function with with generics to delete an object from a array
Typescript arrow function with with generics to delete an object from a array

Time:08-02

I have multiple arrays of objects in different types as follows.

unit:Unit[]=[{id:1,name:'unit 1']

book:Book[]=[{id:1,name:'book1']

To remove objects from the arrays I want to create a general function which should be an arrow function with generics and exporting from another .ts file. So that I can delete any arrays using that function.

I have tried like this

export const deleteFromArray= <T>(arr: T[], value: any) => {
  return arr.filter((val: T) => val['id'] != value)
}

CodePudding user response:

first of all delete is a reserved word in JavaScript, so use a different name. The second thing is that in the arr.filter() method you're creating variable val, but you're using the same name for the argument val. I think name collision is happening.

Hope that helps.

CodePudding user response:

Assuming you are always using id as the filter critera you could extend your generic T by {id: number} by default.

export const deleteFromArray = <T extends {id: number}>(
  arr: T[],
  value: any
): T[] => {
  return arr.filter((val: T) => val.id != value);
};

That way you can use the function like so:

type Book = {
  id: number;
  name: string;
};

deleteFromArray<Book>([{id: 0, name: "myBook"}], 0);
  • Related