Kent Cooper Kent Cooper - 2 months ago 18
TypeScript Question

TypeScript sorting an array

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:

var numericArray:Array<number> = [2,3,4,1,5,8,11];

var sorrtedArray:Array<number> = 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.

Answer

The error is completely correct.

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.