Confusing behaviour with basic type boolean in TypeScript

后端 未结 2 1272
感动是毒
感动是毒 2021-01-25 16:31

From TypeScript webpage: \"The most basic datatype is the simple true/false value, which JavaScript and TypeScript call a boolean value.\"

Ok so far so good, it\'s just

相关标签:
2条回答
  • 2021-01-25 17:30

    See https://github.com/Microsoft/TypeScript/issues/11178#issuecomment-249877718

    This is working as intended. The compiler performs control flow analysis and knows that p has the actual value Place.Left where you're performing the === operations, and it is calling out that it makes no sense to compare a value that is known to be Place.Left to a value that is known to be Place.Right. It's effectively like writing Place.Left === Place.Right or 1 === 2, both of which would also produce errors.

    You get the error message because TypeScript also warns about possible developer errors. As you set a to false (and never change it), it makes no sense to check for a == true as that is never true in your code. Essentially, TypeScripts warns you about dead code.

    0 讨论(0)
  • 2021-01-25 17:33

    you do not need to compare true/false values with ==/=== because they are already boolean values themselves. thus making it redundant.

    so just do if (a) or if (!a)

    typescript just wants to optimize your code this way. in vanilla JS it is perfectly fine to do if (a === true)

    0 讨论(0)
提交回复
热议问题