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?
(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)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With