Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 348
Sara Mesa Avatar asked Jul 26 '18 12:07

Sara Mesa


2 Answers

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.

like image 55
FatalMerlin Avatar answered Oct 01 '22 23:10

FatalMerlin


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

like image 40
ubershmekel Avatar answered Oct 01 '22 22:10

ubershmekel