Type Checking with Unions
What you'll learn: How TypeScript restricts you to only safe operations when working with union types until you narrow them.
The Safety Restriction
When you have a union type, TypeScript doesn't know which specific type you're working with at any given moment. To keep you safe, TypeScript only allows operations that are valid for all possible types in the union.
Think of it like a universal remote that only shows buttons that work on every device it controls. If it can control a TV and a ceiling fan, you'll only see the power button—not channel selection (TV only) or speed control (fan only).
What This Looks Like
function printLength(value: string | number) {
console.log(value.length); // ❌ Error!
// Property 'length' does not exist on type 'number'
}
Even though string has a .length property, number doesn't. TypeScript blocks this because if value were a number, your code would crash.
Only Common Operations Work
function convertToString(value: string | number) {
console.log(value.toString()); // ✅ OK
// Both string and number have toString()
}
The .toString() method exists on both types, so TypeScript allows it.
Why This Matters
This restriction forces you to handle each type case explicitly (through narrowing), preventing runtime errors. TypeScript won't let you assume which type you have—you must prove it first with typeof, truthiness checks, or other narrowing techniques.
Key Takeaway: TypeScript only permits operations that work for every type in a union; you must narrow the union to access type-specific properties or methods.