0
votes

TS is giving me an error in my Angular 7 project for the sort function below. The error message is: "The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type'".

Technically this will work if I comment the function out and then the application run. Once the application is running I can uncomment the function and everything works as expected including the sort function.

Basically I am trying to sort dates on descending order.

    this.SortArray = this.project.Attributes.sort(function (a, b) {

        return new Date(a.EffDate) - new Date(b.EffDate);
      });
1
Since this is TS code it is difficult to answer this without a minimal reproducible example version of your code using an online code editor like codesandbox.io, etc.palaѕн
(new Date(a.EffDate)).valueOf() - (new Date(b.EffDate)).valueOf() Note that a) EffDate should be in ISO 8601 format to work cross-browser and b) sorting alphabetically on ISO 8601 dates works.Heretic Monkey

1 Answers

3
votes

Use the following in your sort function:

return new Date(a.EffDate).getTime() - new Date(b.EffDate).getTime();

TypeScript definitions prevent dates to be compared directly, so you have to convert them into numbers first.