Constraining to Union Members
What you'll learn: How to restrict a generic type parameter to accept only one of several specific object shapes by constraining to a union type.
What This Means
Sometimes you want a generic function or type to work with several different shapes, but not any shape. You've already seen how extends lets you constrain to a single object type. Now, you can constrain to a union of object types, meaning the type parameter must be one of those specific variants—nothing else.
Think of it like a restaurant menu with three meal options. You can choose any of those three, but you can't order something that's not on the menu.
How It Works
Use extends with a union of object types:
type Cat = { species: 'cat'; meow: () => void };
type Dog = { species: 'dog'; bark: () => void };
function handlePet<T extends Cat | Dog>(pet: T): T {
// T must be Cat OR Dog, nothing else
return pet;
}
const myCat: Cat = { species: 'cat', meow: () => console.log('meow') };
const myDog: Dog = { species: 'dog', bark: () => console.log('bark') };
handlePet(myCat); // ✓ Cat is in the union
handlePet(myDog); // ✓ Dog is in the union
// handlePet({ name: 'Bob' }); // ✗ Not Cat or Dog
You've locked the generic to only those shapes. This is especially powerful with discriminated unions, ensuring type-safe handling of known variants.
Why Use This
This pattern combines the flexibility of generics (preserving exact types) with the safety of discriminated unions (only allowing known shapes). You get autocomplete for all variants and catch invalid inputs at compile time.
Key Takeaway: Constraining a type parameter to a union of object types restricts it to one of several specific shapes, combining generic flexibility with union safety.