Constraints with Union Types
What You'll Learn
You'll learn how to use extends with union types to allow only a specific set of type arguments, giving you precise control over what types a generic can accept.
The Core Idea
Sometimes you want a generic that accepts several possible types, but not any type. By combining extends with union types, you can create a constraint that acts like a whitelist: "This generic only accepts types A, B, or C—nothing else."
Instead of saying "T must have this property" or "T must be a number," you're saying "T must be one of these exact types."
How It Works
function processValue<T extends string | number>(value: T): T {
console.log(`Processing: ${value}`);
return value;
}
processValue("hello"); // ✓ Works: string is in the union
processValue(42); // ✓ Works: number is in the union
processValue(true); // ✗ Error: boolean not in union
Here, T extends string | number means T can be string, number, or any literal type derived from them—but nothing else.
Why This Matters
This pattern is perfect when you need flexibility within bounds. For example, an API method that accepts "GET" | "POST" but still preserves the exact string literal:
function apiCall<T extends "GET" | "POST">(method: T): T {
return method;
}
const method = apiCall("GET"); // type is "GET", not string
You get both constraint (only valid HTTP methods) and precision (the exact literal type is preserved).
Key Takeaway: Use extends with union types to limit a generic to a specific set of allowed types, combining flexibility with strict type safety.