TypeScript · module 10 of 21
Type Narrowing
Type narrowing is how TypeScript figures out a more specific type from a broad one using guards or assertions.
What this module covers
4 steps · TypeScript
Step 1. Type Narrowing
Type narrowing is how TypeScript figures out a more specific type from a broad one using guards or assertions. function formatValue(value: string | number): string { if (typeof value === "string") { return value.toUpperCase(); } else { return value.toFixed(2); } } class Cat { meow() { return "Meow!"; } } class Dog { bark() { return "Woof!"; } } function makeSound(animal: Cat | Dog): string { if (animal instanceof Cat) { return animal.meow(); } return animal.bark(); } Use typeof for primitive types (string, number, boolean), instanceof for class instances, the "in" operator to check for object property existence, and type assertions (as) to override inference — carefully, since they bypass checking.
Both branches here actually read `.length` the same way — but TypeScript still requires the narrowing check, because before it, the compiler cannot prove `.length` is safe on both types. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [TypeScript] Narrow the union and return the correct length.
Step 2. Quiz: Type Narrowing
Answer these questions about type narrowing.
typeof narrows primitives, instanceof narrows class instances, and "in" checks for a property's existence. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [TypeScript] Answer the quiz below.
Step 3. Narrow a Union Type
Write a function called describe that takes string | number | boolean and uses typeof guards to handle each type.
A three-way typeof chain like this is the most common real-world narrowing pattern — each branch narrows the union down to exactly one type. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [TypeScript] Does describe use typeof guards for string, number, and boolean?
Step 4. Mini project: Type Narrowing
Write a function called describe that takes string | number | boolean and uses typeof guards to handle each type. Turn the completed challenge into a small standalone project. Add realistic content, clear naming, one edge case or error state, and a short README-style explanation of how the main idea works.
A three-way typeof chain like this is the most common real-world narrowing pattern — each branch narrows the union down to exactly one type. This project stage asks you to apply the same idea without step-by-step scaffolding. In TypeScript, make the state/interaction visible in the UI so completion is easy to verify.
Check yourself: [TypeScript] Does describe use typeof guards for string, number, and boolean?
Loading code lab...