lecture 1 of 110 completed

Narrowing

A check makes a type smaller, and the compiler follows it. Some checks drop values you wanted, and some narrowing is lost before the code that needs it runs.

What you'll learn

  • Which checks narrow a type, and which one drops 0 and empty text
  • How to read the message of a caught error
  • Why narrowing is lost inside a callback, and what the compiler does not follow

A Shelf helper turns a late fee into text. A fee can be missing, so its type is number | null.

function feeLabel(fee: number | null): string {
  if (!fee) {
    return "no fee recorded";
  }
  return fee.toFixed(2);
}

console.log(feeLabel(0.5));
console.log(feeLabel(null));
console.log(feeLabel(0));
0.50
no fee recorded
no fee recorded

The compiler reports nothing. The third line is wrong. A fee of 0 is a real fee, and the helper says none was recorded.

You met narrowing in the Junior track: a check makes a type smaller. !fee is a check, and the compiler follows it correctly. After the if, fee is a number. The problem is what the check means. !fee is true for null, and also for 0. The compiler checked the types. It did not check that you asked the right question.

Say what you mean.

function feeLabel(fee: number | null): string {
  if (fee === null) {
    return "no fee recorded";
  }
  return fee.toFixed(2);
}

console.log(feeLabel(null));
console.log(feeLabel(0));
no fee recorded
0.00

The checks that narrow

You have used two of these already. Here are the four you need in test code.

typeof tells text, numbers and booleans apart. You used it for unions in the Junior track.

Equality removes one exact value. fee === null removes null. status === "returned" leaves only that status.

Truthiness, such as if (fee) or if (!note), removes null and undefined. It also removes 0, empty text and false. Use it only when you want all of those gone.

in asks whether an object has a field. It tells two object shapes apart.

interface Book {
  title: string;
  isbn: string;
}

interface Magazine {
  title: string;
  issue: number;
}

function shelfLabel(item: Book | Magazine): string {
  if ("isbn" in item) {
    return item.title + " (ISBN " + item.isbn + ")";
  }
  return item.title + " (issue " + item.issue + ")";
}

console.log(shelfLabel({ title: "Dune", isbn: "978-0" }));
console.log(shelfLabel({ title: "Orbit", issue: 12 }));
Dune (ISBN 978-0)
Orbit (issue 12)

Inside the if, the compiler knows item is a Book, because only a Book has an isbn. After it, only Magazine is left, so item.issue is allowed.

A caught error is unknown

Every test helper with a try block meets this.

function saveLoan(): void {
  throw new Error("The book is already on loan");
}

try {
  saveLoan();
} catch (error) {
  console.log(error.message);
}
loans.ts(8,15): error TS18046: 'error' is of type 'unknown'.

This is the error from the Junior lecture on unknown, in a new place. The compiler gives a caught error the type unknown, and it is right to. JavaScript can throw any value. throw "stopped" is legal, and text has no message.

Narrow it with instanceof, which asks whether a value was made by a class.

function messageOf(error: unknown): string {
  if (error instanceof Error) {
    return error.message;
  }
  return String(error);
}

try {
  throw new Error("The book is already on loan");
} catch (error) {
  console.log(messageOf(error));
}

try {
  throw "stopped";
} catch (error) {
  console.log(messageOf(error));
}
The book is already on loan
stopped

Inside the if, error is an Error, and message is allowed. A small helper like messageOf is worth having in every test project. This rule is part of the strict setting.

Narrowing is lost inside a callback

This is the case that surprises people, and test code is full of callbacks.

interface Loan {
  book: string;
  returnedOn?: string;
}

function yearsFor(loan: Loan, titles: string[]): string[] {
  if (loan.returnedOn === undefined) {
    return [];
  }
  return titles.map((title) => title + " " + loan.returnedOn.slice(0, 4));
}
loans.ts(10,46): error TS18048: 'loan.returnedOn' is possibly 'undefined'.

The check is right there, three lines above, and the compiler still says the value may be undefined.

The reason is time. A callback is a function that runs later. Between your check and that later moment, other code could set loan.returnedOn to undefined again. The compiler cannot see when the callback runs, so inside it the check no longer counts.

Copy the value into a const before the callback. A const cannot change, so its narrowing stays.

interface Loan {
  book: string;
  returnedOn?: string;
}

function yearsFor(loan: Loan, titles: string[]): string[] {
  const returnedOn = loan.returnedOn;
  if (returnedOn === undefined) {
    return [];
  }
  return titles.map((title) => title + " " + returnedOn.slice(0, 4));
}

console.log(yearsFor({ book: "Dune", returnedOn: "2026-03-01" }, ["Dune"]));
["Dune 2026"]

You will meet this inside test.step, inside forEach, and inside every callback you pass to a framework. The fix is always the same line.

What the compiler does not follow

Narrowing has a limit in the other direction too. Outside a callback, the compiler keeps trusting your check, even after a call that changes the object.

interface Loan {
  book: string;
  returnedOn?: string;
}

function reopen(loan: Loan): void {
  loan.returnedOn = undefined;
}

function returnYear(loan: Loan): string {
  if (loan.returnedOn === undefined) {
    return "not returned";
  }
  reopen(loan);
  return loan.returnedOn.slice(0, 4);
}

console.log(returnYear({ book: "Dune", returnedOn: "2026-03-01" }));
TypeError: Cannot read properties of undefined (reading 'slice')

That compiles, and it stops when it runs. The wording is from the engine in Node and Chrome. The compiler does not look inside reopen to see what it does to the loan.

So narrowing is the compiler following the checks on your lines. It is strict inside a callback and trusting after a function call. In both cases a const copy of the value is the safe form, because nothing can change it.

Remember this

A check narrows a type, and the compiler follows it. Truthiness also removes 0 and empty text, so compare with null or undefined when those values matter. A caught error is unknown, and instanceof Error narrows it. Narrowing of a field is lost inside a callback, so copy the value into a const first.

Reference: Narrowing in the TypeScript Handbook.

now prove it

Reading is the setup. Solve this exercise in the editor. We check your code with the TypeScript compiler. Then we run it on each case and compare what it prints with the expected output.