9
votes

I have this code in JS and I need to make it work in TypeScript.
It keeps saying:

The right hand side of an arithmetic operation must be of type 'any', 'number' or an enum type

sort(field, reverse, primer) {  
    var key = primer ? 
    function(x) {return primer(x[field])} : 
    function(x) {return x[field]};

    reverse = [-1, 1][+!!reverse];

    return function (a, b) {
        return a = key(a), b = key(b), reverse * ((a > b)) - (b > a));
    } 
}

Any ideas?

2
reverse * ((a > b)) this is number * boolean.ASDFGerte
@ASDFGerte yes but - will convert back to numeric. In any case the OP has Typescript code, not JavaScript code.Pointy
@Pointy, yes, and that's exactly what the error message is about, it's a compile time error because he is using an arithmetic operation where the inferred type of one operand is boolean.ASDFGerte
convert any booleans to numbers before applying any arithmeticsAleksey Solovey
@ASDFGerte ah right, good point :) I'm not a Typescript user so I don't have much a feel for what it complains about I guess.Pointy

2 Answers

12
votes

The Problem

(a > b) and (b > a) both return boolean and additionally ((a > b)) has a bracket too much.

To resolve this, both boolean results have to be converted to number. This can be achieved by one of these 3 methods:

1. +bool
2. bool ? 1 : 0
3. Number(bool)

The Solution (using Method #1):

sort(field, reverse, primer) {  
    var key = primer ? 
    function(x) {return primer(x[field])} : 
    function(x) {return x[field]};

    reverse = [-1, 1][+!!reverse];

    return function (a, b) {
        return a = key(a), b = key(b), reverse * (+(a > b) - +(b > a));
    } 
}

Note:

Using (+(a > b) - (b > a)) would not work, since the - will not work as an arithmetic conversion but a subtraction, therefore keeping the type error.

0
votes

I got to this error because I was using Typescript and marked a variable as Number instead of number.

Woops! Typescript docs do mention not to use Number.

https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#the-primitives-string-number-and-boolean

I opened an issue https://github.com/microsoft/TypeScript/issues/45460