operator '===' cannot be applied to types 'false' and 'true'

I know this below code is stupid. But in real time it may possible while compiling with two different data with same type.

if (false === true) {}// getting error

operator '===' cannot be applied to types 'false' and 'true'

But Object.is() is accepting this different data without any error and it returning false

I know the difference between them. But why typescript throwing syntax error as same time why Object.is() not throwing that error.

Also this error message is correct? or not?

operator '===' cannot be applied to types 'false' and 'true. it should be like operator '===' cannot be applied to types 'Boolean' and 'Boolean'

If the message is wrong, then it solved in any upgraded versions? I m using typescript 2.0.3 version.

This problem is occurred in this below scenarios

  • 1

    Object.is("string", "string");
    if ("string" === "string1") {
    }
    
  • 2

    Object.is(1, 2);
    if (1 === 2) {
    }
    

etc..

Answers:

Answer

Typescript is basically throwing an error there because it's bad code.

true will never ever equal false. Typescript knows this, and tells you to fix your code.

Since these are constant values, they're considered to be of the types true and false. The error message might be slightly confusing, but it's correct, while giving a bit of an insight into the Typescript engine.

You'll get a similar error for this code:

if (1 === 2) {}

Error:

Operator '===' cannot be applied to types '1' and '2'.

Comparing constants like these throws that error:

false === true; // Operator '===' cannot be applied to types 'false' and 'true'.
    1 === 2;    // Operator '===' cannot be applied to types '1' and '2'.
  "a" === "b";  // Operator '===' cannot be applied to types '"a"' and '"b"'.

Object.is is completely different from ===. Object.is performs no type coercion, and only compares both parameter's value. Since TypeScript doesn't validate those arguments with the function's functionality, it doesn't throw an error there.

Answer

Check if you have correctly declare your boolean variable , I think you have declared it to false/true instead of Boolean. I hope this could help someone.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.