Extracting Keys from Union Types
What you'll learn: How to use mapped types to pull out specific property names from discriminated unions or complex object unions as reusable type-level values.
The Challenge
When working with union types—especially discriminated unions—you sometimes need to extract just the keys themselves as a new type. For example, given a union of event objects, you might want a type that represents all possible event names, or given different API response shapes, you might want all possible status codes.
How It Works
The pattern combines key remapping (the as clause you just learned) with union iteration. When a mapped type iterates over a union, it processes each union member separately. You can use the as clause to extract specific properties from each member:
type ExtractEventName<T> = {
[K in keyof T]: T[K] extends { name: infer N }
? N
: never
}[keyof T];
This pattern:
- Iterates over each property in the union
- Checks if that property has a specific shape
- Extracts the value you want (like a
nameproperty) - Uses index access
[keyof T]to collect all extracted values into a union
Think of it like filtering a deck of cards: you spread them all out, pick only the specific information from each card (say, the suit), and gather those suits into a new collection.
Practical Example
type Action =
| { type: 'login'; username: string }
| { type: 'logout' }
| { type: 'refresh'; token: string };
type ActionType = Action['type']; // 'login' | 'logout' | 'refresh'
Here, Action['type'] extracts all possible type values from the union—a simple form of key extraction using indexed access.
Key Takeaway: Use mapped types with as clauses and indexed access to extract specific property values from union members, creating focused type-level subsets of your discriminants or other key fields.