Type narrowing

Topic 3 of 5 in Unions and narrowing7 min readIntermediateFree course

Overview

A union says “it could be any of these”. Before you can use member-specific features, you have to find out which one you have. Narrowing is how: you write an ordinary JavaScript check, and TypeScript understands it and refines the type for the code that follows. No casts, no special syntax — just the checks you’d write anyway.

Control flow analysis

Narrowing: the type changes with each check. In function format(value: string | number | null), value starts as string | number | null. Inside if (value === null) { return “—”; } it is null. Inside the following if (typeof value === “string”) branch it is string, so value.toUpperCase() is allowed. After both checks, at return value.toFixed(2), it is number. TypeScript follows your if, return, typeof, instanceof, in and === checks (“control flow analysis”). After each check it knows which types are still possible at that line — no casts needed.

TypeScript reads your code the way you do. After a check, it knows which types are still possible on each path — inside the if, after an early return, in each case of a switch. This is called control flow analysis, and every technique below plugs into it.

typeof

For primitives, typeof is the tool:

TypeScript
function pad(value: string | number) {
  if (typeof value === "number") {
    return " ".repeat(value);    // value: number
  }
  return value;                  // value: string
}

TypeScript understands the results "string", "number", "bigint", "boolean", "symbol", "undefined", "object" and "function". Beware one JavaScript quirk: typeof null is "object", so a typeof x === "object" check doesn’t rule out null — TypeScript knows that and keeps null in the type.

Truthiness

if (value) removes null, undefined and the other falsy values:

TypeScript
function greet(name: string | undefined) {
  if (name) {
    return `Hello, ${name}`;     // name: string
  }
  return "Hello, stranger";
}

Careful: for strings and numbers, "" and 0 are falsy too. If they’re valid values, compare explicitly (name !== undefined).

Equality

Comparing with ===, !==, == or != narrows both sides:

TypeScript
function check(a: string | number, b: string | boolean) {
  if (a === b) {
    // the only type both can share: a: string, b: string
  }
}

function len(text: string | null | undefined) {
  if (text == null) return 0;    // == null matches both null and undefined
  return text.length;            // text: string
}

Comparing against literal values narrows literal unions: after if (size === "sm") return …, size is "md" | "lg".

instanceof

For values created from classes — Date, Error, Map, your own classes:

TypeScript
function toTime(value: Date | string): number {
  if (value instanceof Date) return value.getTime();   // value: Date
  return Date.parse(value);                            // value: string
}

Array.isArray

TypeScript
function toList(input: string | string[]): string[] {
  return Array.isArray(input) ? input : [input];
}

The in operator

For unions of object types, check for a property that only some members have:

TypeScript
type Cat = { name: string; meow(): string };
type Dog = { name: string; bark(): string };

function speak(pet: Cat | Dog) {
  if ("meow" in pet) return pet.meow();   // pet: Cat
  return pet.bark();                      // pet: Dog
}

in also narrows unknown values, as you saw in any, unknown and never: if (typeof data === "object" && data !== null && "port" in data) makes data.port readable.

Assignment

Assigning to a variable narrows it to the type of what you assigned:

TypeScript
let value: string | number = Math.random() > 0.5 ? "a" : 1;
value = "hello";
value.toUpperCase();   // value: string — TypeScript saw the assignment

switch

switch narrows in each case, exactly like a chain of === checks:

TypeScript
function label(size: "sm" | "md" | "lg") {
  switch (size) {
    case "sm": return "Small";
    case "md": return "Medium";
    case "lg": return "Large";
  }
}

Because every case returns, TypeScript knows the function always returns a string. Combined with object unions, switch becomes the main tool of the next lesson.

When nothing is left: never

Each check removes possibilities. When all have been removed, what remains is never:

TypeScript
function format(value: string | number) {
  if (typeof value === "string") return value;
  if (typeof value === "number") return String(value);
  const impossible: never = value;   // ✓ nothing left
}

If someone later adds boolean to the union, that last line fails to compile — pointing straight at the function that needs updating. Discriminated unions uses this trick for exhaustive switch statements.

Where narrowing gets lost

Narrowing applies to a specific variable or property path in a specific place. It resets when TypeScript can’t be sure the value is unchanged:

  • inside callbacks that run later (copy into a const first);
  • after a function call that might modify the object — though TypeScript is optimistic here and usually keeps property narrowing;
  • for different expressions: checking data.items[0] doesn’t narrow data.items[i].

When narrowing doesn’t stick, assign the value to a const, narrow that, and use it.

Writing your own checks

When the built-in checks aren’t enough — say, to check that an unknown value has the shape of a User — you can write a function that narrows. That’s a type guard, covered in Custom type guards.

Remember: write the check you’d write in JavaScript, and TypeScript will follow it. Prefer early returns, use the technique that matches the kind of type, and let never tell you when you’ve covered everything.

Exercise

Describe anything

Write describe(value: string | number | boolean | Date | string[] | null | undefined): string using a different narrowing technique for each case: null/undefined → "empty" (equality with == null); a string → text "…" with its length (typeof); a number → number 3.14 with 2 decimals, or "not a number" for NaN (typeof + Number.isNaN); a boolean → yes/no; a Date → date 2026-12-04 (instanceof); an array → list of 3: a, b, c (Array.isArray). Then write speak(pet: Cat | Dog): string using the in operator. Print a line for each test value in the starter.

TypeScript
type Cat = { name: string; meow(): string };
type Dog = { name: string; bark(): string };

// describe()

// speak()

const values = ["hello", 3.14159, Number.NaN, true, new Date("2026-12-04T00:00:00Z"), ["a", "b", "c"], null, undefined];

Summary

  • Narrowing turns a broad type into a specific one inside a branch; TypeScript tracks it through ifs, returns, switches and loops.
  • typeof narrows primitives; instanceof narrows class instances; Array.isArray narrows arrays.
  • in narrows object unions by checking for a property; ===, !== and == null narrow by value.
  • After all members have been handled, the remaining type is never — useful for exhaustiveness checks.
  • Early returns narrow everything below them, keeping code flat and readable.