0
votes

I have array of object with this interface

interface Item {
country: string;
cases: number;
deaths: number;
population: number;
}

I want to make sort function

const sortDescending = (type: keyof Item): void => {
    data.sort((a, b) => {
    
      return a[type] - b[type];
    });
    
  };

Problem that typescript is not allowing me to perform it because of "The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type" I understand that I have strings in object and I can't do arithmetic operation with them. how to fix it ?

1
So what do you want to do? Limit the sorting function to the number properties, or improve the sorting function so that it also works on strings?Stéphane Veyret

1 Answers

0
votes

Typescript makes us more thoughtful when using arithmetic, if it doesn't looks logical at first glance, it'll throw that error.

    const sortDescending = (type: keyof Item): void => {
      data.sort((a, b) => {
        // add types 'as any' -> or a better type like number | boolean
        return (a[type] as any) - (b[type] as any);
        // (<any>a[type]) can also be an option
       });
    };