简体   繁体   中英

typescript error - 'boolean' is not assignable to type 'number'

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM