TypeScript Reference ยท Type Operators
TypeScript equality and comparison operators
Reference for equality and comparison in TypeScript: === versus ==, Object.is, relational operators, the 'no overlap' error and narrowing by comparison.
TypeScript uses the JavaScript equality operators and adds type checking on top. === and !== compare without conversion; == and != apply JavaScript's coercion rules; <, >, <= and >= compare numbers, bigints or strings.
The compiler also reports comparisons that can never be true, such as comparing two types with no overlap, and it narrows types based on equality checks. That makes === both a runtime test and a type-narrowing tool.
const input: string | number = Math.random() > 2 ? "a" : 1; if (input === 1) { /* input: number here */ }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
a === b a !== b a == b a != b a < b a > b a <= b a >= b
| Operator | Description |
|---|---|
===, !== |
Strict comparison: same type and value. Objects are equal only if they are the same reference. NaN is never equal to itself. |
==, != |
Loose comparison with coercion. null == undefined is true; most other mixed-type comparisons convert to numbers. |
<, >, <=, >= |
Numeric comparison, or lexicographic by UTF-16 code unit when both sides are strings. number and bigint can be compared with each other. |
Result type: boolean.
Errors: error 2367, "This comparison appears to be unintentional because the types 'X' and 'Y' have no overlap", appears when the operand types cannot ever be equal. Relational operators on other mixes such as string < number are also rejected.
Usage notes
- Use
===by default. The one common exception isx == nullto test for bothnullandundefinedin a single check. - Narrowing: equality against a literal narrows unions (
kind === "circle"selects one member of a discriminated union), andx !== undefinedremovesundefined. NaNand-0: useNumber.isNaN(x)orObject.iswhen these matter.Array.prototype.includestreatsNaNas equal to itself,indexOfdoes not.- Objects and arrays compare by reference. Compare contents with a helper or
structuredClone-aware libraries;JSON.stringifyequality is fragile. - Strings sort by code unit, not by language rules; use
localeCompareorIntl.Collatorfor user-facing sorting. - Dates:
d1 < d2works (viavalueOf) butd1 === d2compares identity; comparegetTime()values. - Switch statements use
===semantics.