4

I'm trying to compare to boolean value in a if. I would like to do something like this:

value1 = false;
value2 = true;

if (value1 === value2) {
  ... Some code ...
}

In JAVA you can use Boolean.compare(boolean a, boolean b), but I can't find something equal in TypeScript.
For context, Boolean.compare(boolean a, boolean b) returns:

  • 0 if a is equal to b,
  • a negative value if a is false and b is true,
  • a positive value if a is true and b is false.

Thanks for you help

Edited: to show the message I get

enter image description here

This condition will always return 'false' since the types 'true' and 'false' have no overlap

9
  • What's wrong with what you wrote?
    – tehhowch
    Dec 19, 2020 at 14:42
  • 1
    === is how to compare two boolean values.
    – jonrsharpe
    Dec 19, 2020 at 14:42
  • 1
    === checks for equality. Boolean.compare checks for ordering (returns less than zero if a is false and b is true, zero if they are equal or more than zero if a is true and b is false - is that the behavior you're looking for?
    – Mureinik
    Dec 19, 2020 at 14:42
  • 3
    I've taken the liberty of adding a description for Boolean.compare to your question since it seems you're being downvoted due to being misunderstood.
    – Etheryte
    Dec 19, 2020 at 14:47
  • 1
    dw someone and I upvoted you so at least you won't lose reputation Dec 19, 2020 at 14:57

2 Answers 2

4

Javascript doesn't have a builtin that's comparable to Java's Boolean.compare(). In fact, the Boolean class has nearly nothing in it, outside the constructor, toString() and valueOf().

If you want to replicate the functionality yourself, you can use the Number constructor.

function booleanCompare(a: boolean, b: boolean) {
    return Number(a) - Number(b);
}
1
  • 1
    Thanks so much :) Its exactly what I want
    – JBD
    Dec 19, 2020 at 15:11
0

This can be used to reach all possible outcommings:

const Result = {
  first: 0, // A: 0, B 0
  second: 1, // A: 1, B 0
  third: -1, // A: 0, B 1
  forth: 2, // A: 1, B 1
  get: (A: boolean, B: boolean) => (Number(A) - Number(B))
}

const f = () => {
  const A = true;
  const B = true;

  switch(Result.get(A, B)) {
    case Result.first:
      // To something
      break;
    case Result.second:
      // To something
      break;
    case Result.third:
      // To something
      break;
    case Result.forth:
      // To something
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.