0

so i want to know how to implement or exclusive in type script

my problem is I have two conditions a and b I want to enter if statement only if one of them correct and the other is not

what I have tried is this

if((a==false && b==true) ||  (a==true and b==false)){
DO SOMTHING }

but I want a more clean version

kelsny
  • 23,009
  • 3
  • 19
  • 48

2 Answers2

3

TypeScript prevents using the bitwise XOR on boolean types, even if it would execute because JavaScript converts them to 0 and 1 on the fly. So just go for a !== b.

TypeScript playground

Guerric P
  • 30,447
  • 6
  • 48
  • 86
0

If you are going to use this comparison a lot, you could refactor the expression in a xor function that would return this result

const xor = (a: boolean, b: boolean) => ((a && !b) || (!a && b));

If you're doing a one time and want to save some character space, go for bit manipulation if both a and b are booleans (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_XOR)

if(a ^ b) {
    // your stuff here
}

Though we could argue that bit manipulation might not be the most readable thing ever for someone that has never done it.

Cptn-Tomatoe
  • 116
  • 5