patterntypescriptCritical
TypeScript sorting an array
Viewed 0 times
typescriptsortingarray
Problem
I've been trying to figure out a very strange issue I ran into with typescript. It was treating an inline Boolean expression as whatever the first value's type was instead of the complete expression.
So if you try something simple like the following:
TryIt
You will get an error on your sort method saying the parameters do not match any signature of the call target, because your result is numeric and not Boolean. I guess I'm missing something though cause I'm pretty sure n1>n2 is a Boolean statement.
So if you try something simple like the following:
var numericArray:Array = [2,3,4,1,5,8,11];
var sorrtedArray:Array = numericArray.sort((n1,n2)=> n1 > n2);TryIt
You will get an error on your sort method saying the parameters do not match any signature of the call target, because your result is numeric and not Boolean. I guess I'm missing something though cause I'm pretty sure n1>n2 is a Boolean statement.
Solution
The error is completely correct.
As it's trying to tell you,
You need to return negative if the first item is smaller; positive if it it's larger, or zero if they're equal.
As it's trying to tell you,
.sort() takes a function that returns number, not boolean.You need to return negative if the first item is smaller; positive if it it's larger, or zero if they're equal.
Context
Stack Overflow Q#21687907, score: 233
Revisions (0)
No revisions yet.