Q11: What is Type Narrowing and how do build-in Type Guards work?

Difficulty:EasyTopic:Type Guarding

Type Narrowing is the process where TypeScript refines a broad type (like a union) into a narrower type within a specific code block using logical checks.

Native Guards

  • typeof: Narrow primitive types (string, number, boolean, symbol).
  • instanceof: Narrow class instances.
  • in operator: Check if a property key exists on an object.
  • Truthiness checks (if (val)): Exclude null or undefined.
Key Takeaways
  • Type narrowing leverages standard JavaScript logical conditional checks.
  • TypeScript inspects execution branches to refine types automatically.