All posts

Type Narrowing in TypeScript

How TypeScript goes from a broad type like string | null to a specific one, and why that stops your code from crashing. With live examples you can play with.

Here’s a question that sounds simple: if a variable can be two different types, how does TypeScript know which one it is right now?

Say a name can be a string, or it can be null because the user never filled it in. You want to call .trim() on it. Strings have .trim(). null has nothing at all. So is the call safe or not?

TypeScript’s answer is a feature called type narrowing: going from a broad type (string | null) to a specific type (string) before you do anything risky with it.

The problem: a type with two faces

Here’s a small function. Press Play and try both inputs. Then switch to With a typeof check and try them again.

printName, step by step
Call it with
  1. function printName(name: string | null) {name: string | null
  2. console.log(name.trim());name: string | null
  3. }
Tip: press Play, or click any line to see what TypeScript knows there.

Did you see the crash? Without the check, passing null blows up at run time with a TypeError. The best part is that TypeScript saw it coming. That red squiggly line on name.trim() is the compiler telling you, before you ever run the code:

What the compiler says
function function printName(name: string | null): voidprintName(name: string | nullname: string | null) {
  var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(name.String.trim(): string
Removes the leading and trailing white space and line terminator characters from a string.
trim
());
'name' is possibly 'null'.
}

The compiler isn’t being fussy. It’s being careful. name might be null, and you can’t call .trim() on null.

The fix: check first, then use

Wrap the call in an if that checks the type. Hover over (or tap) name on each line below. These popups come from the real TypeScript compiler, so they show exactly what your editor would show:

Narrowed with typeof
function function printName(name: string | null): voidprintName(name: string | nullname: string | null) {
  // Out here, name could be either type
  if (typeof name: string | nullname === "string") {
    var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
(name.String.trim(): string
Removes the leading and trailing white space and line terminator characters from a string.
trim
());
name: string
} }

Outside the if, name is string | null. Inside it, name is just string. Nothing about the variable changed. What changed is what TypeScript knows about it at that line.

Narrowing with classes: instanceof

typeof works for basic types like string, number and boolean. For objects made from classes, we use instanceof. Here are three classes: an Animal, and a Dog and Cat that extend it. Only dogs can bark, and only cats can meow.

The classes
class class AnimalAnimal {
  constructor(public readonly Animal.name: stringname: string) {}
}

class class DogDog extends class AnimalAnimal {
  Dog.bark(): voidbark() {
    var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
("Woof! Woof!");
} } class class CatCat extends class AnimalAnimal { Cat.meow(): voidmeow() { var console: Consoleconsole.Console.log(...data: any[]): void
The **`console.log()`** static method outputs a message to the console. [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static)
log
("Meow! Meow!");
} }

Now we want one function, makeSound, that takes any animal and calls the right method. Pick an animal and press Play. Then click each line to see what autocomplete offers after animal.:

makeSound, step by step
Pass in
  1. function makeSound(animal: Animal) {animal: Animal
  2. if (animal instanceof Dog) {animal: Animal
  3. animal.bark();animal: Dog
  4. }
  5. if (animal instanceof Cat) {animal: Animal
  6. animal.meow();animal: Cat
  7. }
  8. }
Tip: press Play, or click any line to see what TypeScript knows there.

On the first line, animal is just an Animal, so the only thing you can use is name. Inside if (animal instanceof Dog), TypeScript narrows it to Dog and suddenly bark() shows up. Inside the Cat check, you get meow() instead. Try calling animal.bark() inside the Cat block and the compiler will stop you.

Here’s the full program from the video. It’s a real editor: change anything, hover for types, and press Run.

⚡ The full example
class Animal {
  constructor(public readonly name: string) {}
}

class Dog extends Animal {
  bark() {
    console.log("Woof! Woof!");
  }
}

class Cat extends Animal {
  meow() {
    console.log("Meow! Meow!");
  }
}

function makeSound(animal: Animal) {
  if (animal instanceof Dog) {
    animal.bark();
  }
  if (animal instanceof Cat) {
    animal.meow();
  }
}

const dog = new Dog("Tommy");
const cat = new Cat("Kitty");

makeSound(dog);
makeSound(cat);

Click the code to edit it. TypeScript checks it as you type.

🎉 Nice! No type errors. TypeScript is happy now.

Your turn

This function should print any message in capitals. But numbers don’t have .toUpperCase(), so TypeScript is complaining. Fix it with what you just learned, then press Run.

🧩 Your turn

Hint: check typeof message before calling toUpperCase(). What should happen to numbers?

function shout(message: string | number) {
  console.log(message.toUpperCase());
}

shout("hello");
shout(42);

Click the code to edit it. TypeScript checks it as you type.

🎉 Nice! No type errors. TypeScript is happy now.

Quick recap

  • A union type like string | null means a value can be either type.
  • Type narrowing is how TypeScript goes from that broad type to a specific one before you use it.
  • typeof narrows basic types. instanceof narrows class instances.
  • The compiler follows your if blocks (control flow analysis), so inside the check you get the narrowed type and the right autocomplete.

Narrowing is one of those features you’ll use every single day without thinking about it. Now you know what the compiler is doing behind the scenes.