TypeScript
/Beginner
Union Types
Definition
A Union Type is a type formed from two or more other types, representing values that may be any one of those types. It uses the pipe `|` symbol.
Explain Like I'm New
A Union type is an 'OR' operator for types. It tells TypeScript: 'This variable is allowed to be a String OR a Number. Either one is completely fine.'
Real World Example
A function that finds a user by ID. Sometimes the ID is from a URL (so it's a string '123'), sometimes it's from a database (so it's a number 123). You type the parameter as `id: string | number`.
Common Use Cases
- •Handling diverse inputs
- •API responses that return different shapes based on status
Interactive Example
function printID(id: string | number) { // ERROR: Property 'toUpperCase' does not exist on type 'string | number'. // console.log(id.toUpperCase()); // TYPE NARROWING: if (typeof id === "string") { // Inside this block, TS knows 'id' is definitely a string console.log(id.toUpperCase()); } else { // Inside this block, TS knows 'id' MUST be a number console.log(id.toFixed(2)); } } printID(101); printID("202-A");
Interview Questions
basic
- What symbol is used for Union Types?
intermediate
- If a parameter is `string | number`, can you call `.toUpperCase()` on it immediately?
advanced
- What is Type Narrowing?