DEV Community

Cover image for This Is How I Mastered TypeScript Like I'm 5 (Type Narrowing!)(6)
Karandeep Singh for Wisdom Bits

Posted on

This Is How I Mastered TypeScript Like I'm 5 (Type Narrowing!)(6)

Today! We’re going to continue TypeScript learning like you’re a smart 5-year-old who loves to build things and asks “why?” (which is the best thing ever).

& yes “why?” is my way of learning.

I've divided this into 20 Chapters. and will go one by one and each will be of 2 - 3 min. of read.
This is a Continuation. if you have not read the Previous chapter - Chapter 5

This is Chapter ⓺ TS Mastering

🧩 Chapter 6: Type Narrowing – Becoming a Type Detective

(aka: “Figuring out what type something really is!”)

🧸 Imagine This:

You get a mystery gift 🎁
You know it’s either a teddy bear or a Lego set... but you’re blindfolded!
So you feel the shape and say:

“Aha! It has squishy arms… must be a teddy bear!”

That’s what type narrowing does:
TypeScript helps you figure out the exact type of a variable when it could be more than one.

👀 When do we need this?

When you use union types like:

let value: string | number;
Enter fullscreen mode Exit fullscreen mode

You can’t just say:

console.log(value.toUpperCase()); // ❌ Error!
Enter fullscreen mode Exit fullscreen mode

TypeScript: “Wait… What if it’s a number?”

So you narrow it down:

🔎 1. Using typeof

function print(value: string | number) {
  if (typeof value === "string") {
    console.log(value.toUpperCase()); // ✅ Safe!
  } else {
    console.log(value.toFixed(2)); // ✅ Must be number!
  }
}
Enter fullscreen mode Exit fullscreen mode

typeof checks the kind of value at runtime and narrows it!

🧪 2. Using in for objects

type Dog = { bark: () => void };
type Cat = { meow: () => void };

function speak(pet: Dog | Cat) {
  if ("bark" in pet) {
    pet.bark(); // 🐶
  } else {
    pet.meow(); // 🐱
  }
}
Enter fullscreen mode Exit fullscreen mode

🧱 3. Using instanceof

Works with classes!

class Car {
  drive() {}
}
class Bike {
  pedal() {}
}

function move(vehicle: Car | Bike) {
  if (vehicle instanceof Car) {
    vehicle.drive();
  } else {
    vehicle.pedal();
  }
}
Enter fullscreen mode Exit fullscreen mode

If you enjoyed this and want to master TypeScript and other technologies, follow the series and drop a like!🤝

I’m a passionate software developer sharing the cool things I discover, hoping they help you level up on your coding journey.

How i created my own State Management Library : Rethinking State Management in React — From a Dev, for Developers.

Top comments (2)

Collapse
 
greguzelac profile image
Greg Uzelac •

I see links to jump to the previous chapter but how do I jump to the next chapter?

Collapse
 
karandeepsingh7070 profile image
Karandeep Singh Wisdom Bits •

Hi Greg, appreciate you catching that. I’ll edit the next chapter links in existing articles going forward. for now you can check through visiting the profile.