Codectionary / Developer documentation / TypeScript

Narrowing by Equality

An equality check can narrow two variables to the alternatives their types share.

What it is and why to use it

An equality check can narrow two variables to the alternatives their types share. Literal comparisons also identify specific union cases. This is useful when two independently typed values need an operation that is valid only when they represent the same kind of value.

Common mistakes and limitations

Object equality checks identity, not deep structural equality. Strict equality does not convert a numeric string into a number. Do not assume that matching display text means two separately created objects are equal.

Run this example

Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.

Terminal — compile and run

npx tsc example.ts --strict --target ES2022 --module commonjs
node example.js

Syntax

if (left === right) { /* shared possibilities */ }

Examples

Narrowing by Equality

Standalone TypeScript 5.8+ example; expected output is explained below.

function shared(left: string | number, right: string | boolean): string {
  if (left === right) return left.toUpperCase();
  return "Different";
}
console.log(shared("ready", "ready"));
console.log(shared(3, true));
  1. The only common type between the two unions is string.
  2. Inside the equal branch both values must therefore be strings, so toUpperCase is valid.
  3. The unequal case returns a fallback. This uses runtime strict equality while the compiler tracks the resulting type information.
  4. Expected output: READY Different

Best practices

  • Object equality checks identity, not deep structural equality. Strict equality does not convert a numeric string into a number. Do not assume that matching display text means two separately created objects are equal.
  • Keep external-input validation separate from compile-time type descriptions.

Runtime & versions

Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

TypeScript Handbook

Specifications & further reading