Course contentsShow
← TypeScript
Lesson 394 of 1,7969. Union TypesFree lesson

Equality Checks as Narrowing

How === and !== comparisons narrow unions by eliminating impossible branches.

Equality Checks as Narrowing

You'll learn how simple === and !== comparisons automatically eliminate impossible types from a union.

The Core Idea

When you compare a value against a specific literal using strict equality (=== or !==), TypeScript understands what that means for the type. If you check whether a union type equals a specific value, TypeScript narrows the type in the true branch to only that value, and in the false branch to everything except that value.

This is incredibly powerful for unions of literal types.

How It Works

type Status = "success" | "error" | "pending";

function handleStatus(status: Status) {
  if (status === "success") {
    // TypeScript knows: status is ONLY "success" here
    console.log(status); // type: "success"
  } else {
    // TypeScript knows: status is "error" | "pending" here
    console.log(status); // type: "error" | "pending"
  }
}

TypeScript follows the logic: if status === "success" is true, then status must be "success". If it's false, it cannot be "success", leaving only the other possibilities.

Not-Equal Works Too

function checkStatus(status: Status) {
  if (status !== "pending") {
    // status is "success" | "error"
    console.log(status);
  } else {
    // status is "pending"
    console.log(status);
  }
}

The !== check eliminates the matched type from the union, leaving the rest.

Why This Matters

Think of equality checks as filters that divide your union into "this specific thing" and "everything else." TypeScript tracks these divisions through every branch of your code, giving you precise types without manual assertions.

Key Takeaway: Strict equality checks (=== and !==) against literal values automatically narrow unions by eliminating impossible branches, making your code safer and your types more precise.