Using comparison operators on values of different types is usually an error, so TypeScript warns about that:
if (1 === "1") {} // error
TypeScript treats numeric and string literals as their own types, so comparing two different literals will be an error for the same reason:
if (1 === 2) {} // error
Note that comparing two literals in JavaScript is usually guaranteed to have a known outcome. There's only one possible result for (1 == 2)
. So generally there's not much use to writing that code since you can replace it with its known outcome: (1 == 2)
can be replaced with false
, and (1 === 1)
can be replaced with true
. And so, there's not much of a reason for the language maintainers to care about adding support for comparing two different literals... it's hard to imagine a valid use case for comparing literals that isn't better served by not comparing literals.
However, if you really need to make such a comparison you can widen (one of) the literal types to their common supertype, like number
or string
:
if (1 as number == 2) { console.log("nope"); } // works
if ('1' as string == '2') { console.log("nope"); } // works
You are telling TypeScript to consider 1
not as the literal 1
but as a number
, and that can be compared to 2
. But again, you don't really need to do that. Instead, you can do:
if (false) { console.log("nope"); } // unreachable code detected!
That new warning is also a good one. Usually, unreachable code is a sign of an error. Personally I'd rather just comment that code out or remove it than leave unreachable code. Or just leave the error as a reminder that you should go back and clean it up.
However, if you really want an if (false) {}
scenario to work without an error, the more idiomatic way to do it would be something like
if (false as boolean) { console.log("nope"); } // works
where you're telling the compiler to consider false
to be just a boolean
, and therefore it no longer realizes or cares that the code after the conditional is unreachable.
Hope that makes sense.