Description
Comparing a string to a number generates a TypeScript error saying we can not apply a comparison operator to strings with numbers. This is misleading, since if I truly could not apply a comparison operator to strings with numbers, I could not do that even if a string is part of a bigger union. This results in a perceived inconsistency:
const s = "s"
if (s > 0) {} // Comparing strings to numbers, TypeScript error “can not do that”
const u = (0 as number | string)
if (u > 0) {} // Comparing strings to numbers sometimes, no TypeScript error
The real motivation behind the compiler warning is not the concern about comparing incomparable types, but rather that comparing strings to numbers results in a constant condition. (#13863 (comment)) This resolves the inconsistency between the two similar pieces of code, but it introduces an inconsistency between the error message and the error meaning.
If it was possible to rephrase the error to say “This condition will always return false” or “This condition is constant”, like in case of if (0 !== "")
, the motivation would be immediately self-evident and not mislead.
TypeScript Version: v4.1.0-insiders.20200910
Search Terms: operator can not be applied, number, bigger, less, comparison operator, union.
Code
const s = "s"
if (s > 0) {}
Expected behavior: An error “This condition will always return false” on line 2.
Actual behavior: An error “Operator '>' can not be applied to types 'number | string' and 'number'” on line 2.
Playground Link
Related Issues: #13683