short version:
==
can do unexpected type conversions, in Javascript 1=="1"
is true
. The ===
operator avoids this. Comparing different types with ===
is always false
.
The typescript compiler will emit an error message when you compare different types with ==
. This removes the unexpected type conversions that can happen with ==
in Javascript.
This is a case where valid Javascript leads to an error message in the typescript compiler. The idea that all valid Javascript is also valid Typescript is a common misconception. This is simply not true.
longer version:
I think the accepted answer is misleading. Typescript actually does fix ==
vs ===
(as far as possible at least).
In Javascript there are two comparison operators:
==
: When comparing primitive values, like numbers and strings, this operator will apply a type conversion before doing the comparison. 1 == "1"
evaluates to true
.
===
: This operator does not do type conversions. If the types don't match it will always return false
.
Also, both operators will compare reference types based on their references. Two separate objects are never considered equal to each other, even if they store the same values:
let a = {val:1};
let b = {val:1};
c = a;
a==b; // false
a===b; // false
a==c; //true
a===c; //true
So there you have the two common sources of errors in Javascript comparisons:
- comparing different types with
==
can lead to unexpected type conversions.
- comparing objects and arrays is based on references not values stored inside.
As the existing answer already says, Typescript is designed as a superset of Javascript. So it doesn't change the behaviour of these comparison operators. If you write ==
in Typescript, you get type conversions.
So how is this fixed? With the compiler. If you actually do write code that compares incompatible types with ==
it's a compiler error. Try compiling the following sample:
let str = "1";
let num = 1;
console.log(str == num);
The compiler will tell you:
comparisons.ts:4:13 - error TS2367: This condition will always return 'false' since the types 'string' and 'number' have no overlap.
4 console.log(str == num);
~~~~~~~~~~
Found 1 error.
It is a common misconception that any valid Javascript is also valid Typescript. This is not true and the code above is an example where the typescript compiler will complain about valid Javascript.
This fixes the first of the two sources of errors: unexpected type conversions. It doesn't deal with the second source of errors: comparisons based on references. As far as I know, when you want to do a comparison based on values stored by the objects, you simply can't use these operators. You'll have to implement your own equals()
method.
Also, you may have noticed that the compiler error is wrong. The comparison will not always evaluate to false. I think this is a bug in typescript and have filed an issue.