I need help creating a pipe that can sort an array of objects based on a specified property. While I have managed to make it work, I am encountering a type error in my code. Here is the snippet:
export const sortByProperty = <T>(a: T, b: T, property: keyof T): number => {
if (isNaN(a[property])) return isNaN(b[property]) ? 0 : -1; // error: Type 'T[string]' is not assignable to type 'number'
if (isNaN(b[property])) return 1;
return a[property] - b[property]; // error: The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
};
@Pipe({
name: 'sortBy',
standalone: true
})
export class SortByPipe implements PipeTransform {
transform<T>(items: T[], property: keyof T): T[] {
return [...items].sort((a, b) => sortByProperty(a, b, property));
}
}
Here is an example of how to use it:
<div *ngFor="let product of productList | sortBy: 'value'">...</div>
The data in productList
looks like this:
productList = [
{ order: 0, value: 10, title: 'some product' },
{ order: 1, value: 1000, title: 'some other product' },
{ order: 2, value: 50, title: 'a great product' },
];
The issue here is that the specified property
can be any of the properties of items in the productList. However, I want to restrict it to only properties that will contain numerical values to avoid errors. You can see the problem in action in this Stackblitz example. (remove the a
in front of @ts-ignore
to see it working)