Frontend Developer interview question
How does TypeScript type narrowing work?
TypeScript narrows a union after runtime checks such as typeof, in, equality checks, or discriminated union tags. The narrowing is static safety, so the runtime check still must reflect real data.
Direct answer
What a strong answer covers
How it works
Narrowing is control-flow analysis: inside a branch guarded by typeof, instanceof, in, an equality check, a truthiness test, or a user-defined type predicate, the compiler treats a union as the smaller set of members that could reach that point. Discriminated unions make this reliable by giving each variant a literal tag. Because the check is erased at runtime, narrowing is only as trustworthy as the data actually matching the declared types.
Example
A switch on kind lets TypeScript expose only the fields for that variant and flags an unhandled future variant. Adding a default branch that assigns the value to never turns a forgotten case into a compile error when a new variant is introduced, instead of a silent fallthrough.
Common mistakes
- Narrowing a value from an API response without validating it at the boundary.
- Losing narrowing inside a callback because TypeScript cannot prove the variable was not reassigned.
- Using type assertions to silence the compiler instead of writing the check that narrows.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.