TypeScript inherits this feature from JavaScript, which is why even though TypeScript uses specific types, it still has both ==
and ===
. TypeScript will usually mark an error if you make a comparison between unrelated types. For example both "hello" == 1
and "hello" === 1
are marked as an error in TypeScript code, as it presumes this is a mistake. If you really intend to make such a comparison, then explicitly convert one of the values.
It's generally regarded as best practice to prefer the strict equality comparisons ===
and !==
. This is also a best practice in JavaScript, and in TypeScript generally you want to ensure you are working with specific types and avoid anything that might automatically convert types as that may lead to confusing results. For that reason, the rest of this guide will prefer using strict comparisons.
The less/greater operators don't have strict equivalents, but for those, TypeScript enforces that both sides must be the same type. For example "hello" < 1
is an error in TypeScript code.
It's also worth noting strings can be compared as less or greater. A string is considered less than another string if it would precede it in sort order. For example "apple" < "banana"
is true
because apple would come before banana in a sorted list (as this comparison is based on an alphabetical sort order).