13

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

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

Comments

4

One clean way to think about it:

function xor(a: any, b: any) { return !!a !== !!b; } if (xor(foo, bar)) { // DO SOMETHING } 

I still recommend to test this function before using it, particularly with arrays.

Good luck.

Comments

2

Typescript in this sense is a subset of javascript. It compiles into javascript, but you already know this.

The compiler is just a computer program following orders, and the orders concerning the '^' operator are:

4.15.1 The *, /, %, –, <<, >>, >>>, &, ^, and | operators

These operators require their operands to be of type Any, the Number primitive type, or an enum type. Operands of an enum type are treated as having the primitive type Number. If one operand is the null or undefined value, it is treated as having the type of the other operand. The result is always of the Number primitive type.

(from the specs)

I think the option you give in the update is the answer to your question about alternatives.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.