What is the difference between type widening and type narrowing?
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.