gpt4 book ai didi

sorting - typescript 中排序错误的类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:14:50 26 4
gpt4 key购买 nike

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

给我以下错误:

'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'.'

我应该如何解决这个问题?

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

最佳答案

这不是怎么来的Array.sort作品。您需要返回一个数字,但您给出的谓词返回一个 bool 值(小于 (<) 运算符的结果为 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;
}

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

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

假设leaves输入正确所以 ab正确推断出它们的类型。

关于sorting - typescript 中排序错误的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43668248/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com