Common Properties Access
What you'll learn: When working with union types, you can safely access any property that exists on all members of the union.
The Shared Property Rule
When TypeScript sees a union type, it ensures type safety by only letting you access properties that are guaranteed to exist. Think of it like a Venn diagram: you can only reach the overlapping middle section without narrowing first.
If you have type A = { name: string; age: number } and type B = { name: string; email: string }, then A | B gives you guaranteed access to name because both shapes have it. But you cannot access age or email directly—they're not common to both.
How It Works in Practice
When you declare a union type, TypeScript analyzes all the members:
type Cat = {
name: string;
meow: () => void;
};
type Dog = {
name: string;
bark: () => void;
};
type Pet = Cat | Dog;
function greet(pet: Pet) {
console.log(pet.name); // ✓ Safe: both Cat and Dog have 'name'
// pet.meow(); // ✗ Error: only Cat has 'meow'
// pet.bark(); // ✗ Error: only Dog has 'bark'
}
The name property exists on both Cat and Dog, so TypeScript allows access. The specific methods meow and bark require narrowing first (which you'd do with type guards).
Key Takeaway: TypeScript only allows property access on union types if that property exists on every single member of the union—this guarantees runtime safety without requiring type narrowing.