Description
Bug Report
🔎 Search Terms
double triple == coercion check 2367
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about 'Common "Bugs" That Aren't Bugs' and 'Common Feature Requests'
⏯ Playground Link
Playground link with relevant code
💻 Code
Consider the following valid JavaScript code:
function isIntString(strIn/*: string*/) {
return (strIn == parseInt(strIn));
}
console.log('Result for "14" is ' + isIntString('14'));
console.log('Result for "14x" is ' + isIntString('14x'));
This runs fine, with the following output:
Result for "14" is true
Result for "14x" is false
Then, uncomment the type and rename the file to .ts (or use the playground link above).
🙁 Actual behavior
TS throws an error on the return line saying This condition will always return 'false' since the types 'string' and 'number' have no overlap.ts(2367)
.
This is wrong because there is a difference between the ==
and ===
operator; this is a case where the difference between those two matters and the type coercion is part of the program.
This is another example of where developers have to rewrite valid JavaScript when converting to TypeScript because of a bug in TypeScript, in this case being overly strict about its assumptions that fail to account for type coercion. In this case, it’s not completely clear what the previously valid JavaScript should be rewritten to.
Further, classifying this (especially this false positive) as an error that blocks compilation instead of a warning seems frustratingly unnecessary. There are times in development when it's useful to write something with the effect of if(true)
or if(false)
for testing purposes. Typescript allows if('a' === 'a')
without a problem but throws this compilation-blocking error on if('a' === 'b')
despite the latter being just as much of an issue as the former.
🙂 Expected behavior
At least: TypeScript recognizes that ==
is not the same as ===
and disables/doesn't throw error ts(2367) on ==
comparisons.
At best: In addition, ts(2367) is no more than a warning and does not block compilation.
Related issues
#35925 is an issue related to the comparison between boolean
and number
types closed as “won’t fix” without comment or explanation.