Q25. What is a type guard?
A type guard is a runtime condition that narrows a value's type in a control-flow branch. Built-in examples include typeof, instanceof, in, and equality checks; user-defined predicates can express domain-specific guards.
The guard both executes at runtime and gives the compiler evidence for a narrower type.
Note
Interview approach: define the concept, explain why it matters, then mention one trade-off or limitation.
TypeScript concept
// Illustrative TypeScript contract
type Identifier = string;
const id: Identifier = "item-1";💡 The example demonstrates the compile-time contract discussed in this question.
Key Takeaways
- Explain the concept in your own words.
- Know the practical trade-off and its limits.
- Use a small example to demonstrate the idea.
Knowledge Check
Which is a built-in TypeScript narrowing check?