Comparing Variables

This lesson explains how TypeScript compares variables.

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 ❌

Press + to interact
let value1String: string = "1";
let value1Number: number = 1;
if (value1String == value1Number) { // Culprit
console.log("TypeScript doesn't compile");
}

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 ...