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;
You can’t just say:
console.log(value.toUpperCase()); // ❌ Error!
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!
}
}
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(); // 🐱
}
}
🧱 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();
}
}
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.
I see links to jump to the previous chapter but how do I jump to the next chapter?