Typecript中排序错误的类型

Nic*_*icy 2 sorting typescript typescript2.0

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

给我以下错误:

'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'.'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

编辑:js代码(原始)取自:https: //github.com/atomicptr/goap/blob/gh-pages/gameplay/ai/planner.js,它确实似乎按bool而不是数字排序.

Paa*_*rth 12

这不是Array.sort的工作原理.您需要返回一个数字,但是您给出的谓词返回一个布尔值(小于(<)运算符会返回true或false).排序顺序取决于函数返回的数字是负数,正数还是零.MDN示例通过示例比较函数说明了这一点.

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;
}
Run Code Online (Sandbox Code Playgroud)

如果你想升序排序,你可以这样做

var cheapest = leaves.sort((a,b) => a.cost - b.cost);
Run Code Online (Sandbox Code Playgroud)

假设leaves输入正确,ab正确推断其类型.