Reputation: 87
I am using TypeScript version Version 4.7.3. I am using the Equality Comparison with number and string.Below is the code
let a:number = 10;
let result = a=='10';
I am getting below compilation error.
This condition will always return 'false' since the types 'number' and 'string' have no overlap.ts(2367)
Upvotes: 0
Views: 1258
Reputation: 51034
This is a known bug (see #26592); basically, ==
and ===
are treated the same for the purpose of this error message. To be clear, the bug is that the error message is wrong.
Typescript is supposed to be strongly-typed, so the use of type coercion is discouraged, even though it's valid in Javascript. If you want to compare a number and a string, then (from Typescript's perspective) instead of writing n == s
, you should write String(n) === s
or n === Number(s)
; or, make the two variables the same type in the first place.
So, a better error message would be something like "==
operator on types number
and string
may be a mistake", although in my opinion, you just shouldn't use ==
at all.
Upvotes: 1