Comparing Variables
Explore how TypeScript manages variable comparisons by value and reference, emphasizing strict equality to avoid type conversion issues. Understand structural typing, differences between null and undefined, and best practices for safe comparisons to write more reliable code.
We'll cover the following...
Comparing by value or by reference?
TypeScript inherited its lax comparison rules from Javascript. As we saw earlier, TypeScript reduces potential JavaScript quirks by increasing strictness. However, nothing forces developers to employ the “triple equals” comparison, which is key in avoiding the type conversions that may take place when using “double equals”. TypeScript helps with “double equals” by removing some edge cases.
For example, comparing a number with a number in a string works fine in JavaScript, but won’t compile with TypeScript. On line 1 we declare a string initialized with the value "1" and on line 2, we define a number with the value 1. What is happening on line 3 is a comparison that is always false. The reason is that a string and a number cannot be equal in value: they do not have the same type as a starter.
📜 Note: the code below throws an error ❌
Primitive type compares by value. On the other hand, object literal, class objects, and arrays all compare by reference.
In the following code, line 3 compares two objects that have the exact structure and values. Yet, it is not equal; the reason is that both objects are different because they are both initialized at two different places (lines 1 and 2).