Creating Option Types from Unions
What you'll learn: How to use mapped types to transform each member of a union into a wrapped "option" or "result" type, creating type-safe variants for success/error handling.
The Core Idea
Imagine you have a union of entity types: User | Post | Comment. You want to create a type where each becomes wrapped in a loading state, like { type: 'User', data: User, loading: boolean }. Instead of manually writing three separate types, you can use a mapped type to iterate over the union and wrap each member automatically.
This pattern is powerful for creating option types (like Some<T> and None) or result types (like Success<T> and Error<E>) from unions.
How It Works
When you use a mapped type with a union as its input, TypeScript distributes the mapping across each union member:
type WrapInOption<T> = {
[K in T]: { type: K; value: K }
}[T];
type Entity = 'user' | 'post' | 'comment';
type EntityOption = WrapInOption<Entity>;
// Result: { type: 'user'; value: 'user' } |
// { type: 'post'; value: 'post' } |
// { type: 'comment'; value: 'comment' }
The [T] at the end indexes into the mapped object, extracting the union of all property values.
Practical Pattern: Result Types
type Result<T> = {
[K in T]: { status: 'success'; data: K }
}[T];
type Response = Result<User | Post>;
// Becomes: { status: 'success'; data: User } |
// { status: 'success'; data: Post }
Key Takeaway: Mapped types distribute over unions, letting you wrap each union member in a container type systematically—perfect for creating option/result patterns from entity unions without repetitive code.