What is the difference between type widening and type narrowing?
Why Interviewers Ask This
This question targets practical, hands-on experience with TypeScript. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
Type widening is TypeScript's behavior of inferring a broader type than the literal value when a variable is mutable. When you write let x = "hello", TypeScript widens the type to string (not the literal "hello"), because let allows reassignment. With const x = "hello", TypeScript keeps it as the literal type "hello" because const cannot be reassigned. Widening also happens with null — in some contexts, TypeScript widens null to string | null. You can prevent widening with as const: const colors = ["red", "green"] as const keeps it as a readonly tuple. Type narrowing is the opposite — starting from a broad type (like a union) and using type guards, checks, and control flow to refine it to a more specific type within a block of code. Narrowing goes from wide to specific; widening goes from specific to wide. TypeScript's control flow analysis automatically performs narrowing based on conditionals, assignments, and runtime checks.
Common Mistake
Candidates often give textbook answers here. Interviewers are more impressed when you relate the concept to a specific problem you solved in a real TypeScript project.