12. Union, Literal Types & Type Narrowing
Handling Dynamic Data Safely
Real applications don't always deal with single, predictable data types. An API might return a string if it succeeds, but a number (like a 404 status code) if it fails. We need a way to tell TypeScript that a variable can legitimately be more than one thing.
Union Types
A Union Type allows you to combine multiple types together. You use the pipe character | (meaning "OR") to define it.
Literal Types
Sometimes defining a variable as a `string` is too broad. If you have a user role system, the role shouldn't just be any string (like "banana"); it should only be specific, exact strings. These are called Literal Types.
The Problem with Unions
Unions are flexible, but they introduce a problem. If TypeScript knows a variable is string | number, it will stop you from using string-specific methods on it, because what if it happens to be a number at runtime? It would crash!
Type Narrowing (The Solution)
To safely interact with a union type, you must narrow it down to a specific type using standard JavaScript logic (like `if` statements). TypeScript is incredibly smart—it reads your `if` statements and automatically narrows the type inside that block of code.
Knowledge Check
Ready to test your understanding of 12. Union, Literal Types & Type Narrowing?