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 ❌

Get hands-on with 1200+ tech skills courses.