← TypeScript Foundations
12 / 25
Lesson 12 — Narrowing with in
Tell shapes apart with in
When a union is made of different object shapes, typeof says "object" for all of them. The in operator checks whether a property exists: "r" in s. TypeScript uses that check to narrow — inside the if, s is known to be the shape that has r.
type Cat = { meow: () => void };
type Dog = { bark: () => void };
function speak(p: Cat | Dog) {
if ("bark" in p) p.bark(); else p.meow();
}
Why it matters: API responses often come in several shapes, and in is the clean way to handle each one.
Want it another way?
Task
Use "r" in s to compute the right area: square side 4 → 16, circle r 1 → 3.14.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.