1. Concept library
  2. JavaScript & TypeScript
  3. Module 4: Narrowing and control flow

Concept

typeof and in guards

A type guard is a runtime check TypeScript understands: typeof for primitives, in for properties, instanceof for classes. After the check, the variable has the narrower type inside that branch.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a type guard is and how TypeScript narrows after one
  2. Write typeof, in and instanceof checks that narrow a union
  3. Spot why typeof cannot tell null from an object

In practice

A few lines that show typeof and in guards doing its job.

TypeScript
function describe(value: string | number | Date) {
  if (typeof value === "string") return value.toUpperCase();
  if (value instanceof Date) return value.toISOString();
  return value.toFixed(1);                 // number here
}

type Cat = { meow(): void }; type Dog = { bark(): void };
function speak(pet: Cat | Dog) {
  "meow" in pet ? pet.meow() : pet.bark();
}

The common mistake

Watch for

Expecting typeof to tell null from an object. typeof null is "object", so check value === null first, or use a truthiness check when null and undefined are both possible.

What to know first

Your roadmap puts these before typeof and in guards, unless you already know them.

How it stays learned

Once a session shows you understand typeof and in guards, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled

Where it leads

Topics that build on typeof and in guards.

Next in the moduleDiscriminated unions →