Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript Boolean XOR -- error TS2113: The left/right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type

Tags:

typescript

I have the following code:

var a: boolean = ...;
var b: boolean = ...;

if (a ^ b) { // this line gives error
  // ...
}

However, the TypeScript compiler is giving an error:

error TS2113: The left-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type.

Is it because bitwise operators only work for number? The code runs perfectly fine if written directly in JavaScript.

Is there any alternatives other than if (a ? !b : a) { ... }?

Update Given that both of them are boolean, I could just use a !== b

like image 987
Lucius Avatar asked Jan 17 '14 07:01

Lucius


1 Answers

As you suggest, the ^ operator along with all the other bitwise operators can only be applied to the number type, according to the TypeScript spec.

The only workarounds I know of are:

  • Casting: <number><any>a ^ <number><any>b
  • Negated equality: a !== b

I opened an issue to track this on GitHub:

https://github.com/Microsoft/TypeScript/issues/587

like image 92
Drew Noakes Avatar answered Sep 21 '22 15:09

Drew Noakes