Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrong type with sort in Typescript

var cheapest = leaves.sort((a,b) => <boolean>(<number>a.cost < <number>b.cost));
//also tried without casting

Gives me the following error:

'Error'
message: 'Argument of type '(a: any, b: any) => boolean' is not assignable to parameter of type '(a: any, b: any) => number'.
Type 'boolean' is not assignable to type 'number'.'

How should i fix this?

Edit: The js code ( original) is taken from : https://github.com/atomicptr/goap/blob/gh-pages/gameplay/ai/planner.js , which indeed seems to sort by bool instead of number.

like image 266
NicoJuicy Avatar asked Nov 29 '22 22:11

NicoJuicy


2 Answers

This is not how Array.sort works. You need to return a number, but the predicate you've given returns a boolean (The less than (<) operator results in true or false). The sort order is determined by whether the number your function returns is negative, positive, or zero. The MDN example illustrates this well with an example compare function.

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

If you want to sort ascending you can do this with

var cheapest = leaves.sort((a,b) => a.cost - b.cost);

assuming that leaves is typed correctly so a and b have their types correctly inferred.

like image 131
Paarth Avatar answered Dec 04 '22 06:12

Paarth


The comparator function of a sort should return -1, 0, or 1. Returning a boolean instead (effectively 1 or 0) will fail to sort the list correctly!

For example, in Chrome (sort implementations are host-dependent), this line:

[1, 2, 5, 6, 5, 5, 4, 3, 2, 1, 4, 2, 4, 6, 3].sort(function(a, b) { return a < b; })

Produces:

[3, 3, 5, 6, 5, 5, 4, 6, 4, 4, 2, 2, 2, 1, 1]

Which is not sorted!

You should write something like a > b ? 1 : a === b ? 0 : -1 instead

like image 26
Ryan Cavanaugh Avatar answered Dec 04 '22 08:12

Ryan Cavanaugh