最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - typescript error - 'boolean' is not assignable to type 'number' - Stack Overflow

programmeradmin1浏览0评论

Can anybody help me.

I am trying to sort strings from array

var someArray= ["3a445a_V1", "3", "2a33s454_V1", "1", "3_V2", "2s4a34s3_V2", "234343"];

const [record] = someArray.map(r => parseFloat(r.replace('_V','.'))).sort((a,b) => a < b);

console.log(record)
//it returns 3a445a.1

JFIDDLE

In browser console.log it works fine, not in typescript?

typescript it is giving below error Error:

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

Any idea? thanks in advance

Can anybody help me.

I am trying to sort strings from array

var someArray= ["3a445a_V1", "3", "2a33s454_V1", "1", "3_V2", "2s4a34s3_V2", "234343"];

const [record] = someArray.map(r => parseFloat(r.replace('_V','.'))).sort((a,b) => a < b);

console.log(record)
//it returns 3a445a.1

JFIDDLE

In browser console.log it works fine, not in typescript?

typescript it is giving below error Error:

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

Any idea? thanks in advance

Share Improve this question edited Feb 11, 2018 at 14:25 Manjunath Siddappa asked Feb 11, 2018 at 14:17 Manjunath SiddappaManjunath Siddappa 2,1572 gold badges23 silver badges42 bronze badges 4
  • 3 (a,b) => a < b is not a valid comparison function. As typescript says, it's supposed to return a number, not a boolean. – melpomene Commented Feb 11, 2018 at 14:20
  • "In browser console.log it works fine' It doesn't, actually, it just happens that your data don't reveal the problems with it. – T.J. Crowder Commented Feb 11, 2018 at 14:20
  • @T.J. Crowder , i have just created fiddle, please check and guide me – Manjunath Siddappa Commented Feb 11, 2018 at 14:23
  • 1 @t.j. im still wondering how i overlooked that... – Jonas Wilms Commented Feb 11, 2018 at 14:27
Add a comment  | 

2 Answers 2

Reset to default 19

.sort((a,b) => a < b) is incorrect. The TypeScript message is right: The sort callback should return a number, not a boolean.

Instead: .sort((a,b) => a - b) (- instead of <). Or b - a to sort the other way. This is because the sort callback should return a negative number if a comes before b, 0 if their order doesn't matter, and a positive number if b comes before a. Since you seem to want ascending order, that's a - b so that if a is less than b, it returns a negative number, etc. b - a does a descending sort.

you can also use .sort((a,b) => Number(a>b)). This worked for me just fine.

发布评论

评论列表(0)

  1. 暂无评论