Issue
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)
}
Solution
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);
Answered By - Behemoth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.