Type Narrowing
Narrow means look closer until you know which one it is.
Start with a wide type like string | number.
Then use checks so TypeScript unlocks the right tools.
That is safer than guessing with assertions.
typeof checks
typeof works well for primitives.
A primitive is a simple value like string, number, or boolean.
After the check, TypeScript knows which branch you are in.
Truthiness and equality
Truthiness means asking if a value is present and not empty.
Equality checks compare to exact values.
Both can narrow unions.
in and instanceof
The in operator checks if a property exists.
instanceof checks if a value was made by a class.
Use them to tell object shapes apart.
Type predicates
A type predicate is a helper function that tells TypeScript the type.
Write the return type as value is Type.
After a true result, the value is narrowed.
Control flow analysis
TypeScript follows your if and return paths.
Early returns remove impossible types below.
That is called control flow analysis.
Analysis means careful looking.
Narrow with checks. Let TypeScript follow your ifs. Prefer that over force casting.
Test yourself
Three quick questions made just for this lesson. Earn 10 XP per correct answer.