Mapping Union Values Not Keys
What you'll learn: How to use mapped types to transform union types into object property values instead of property names.
The Core Idea
So far, you've seen mapped types iterate over unions to create property keys — like turning "name" | "age" into an object with those properties. But what if you want a union like "success" | "error" to become the values of properties, not the keys themselves?
This flips the mapped type pattern: instead of [K in Union]: SomeType, you'll typically use a different approach where the union appears on the right-hand side of the type definition.
The Technique
The most common pattern uses Record or similar constructs where you specify the keys explicitly, and map the union into the value position:
type Status = "success" | "error" | "loading";
// Not mapping Status to keys, but to values
type ApiResponse<T> = {
[K in T extends string ? T : never]: {
status: Status;
data: K;
}
};
Another approach: create objects where each property holds one variant of the union:
type EventType = "click" | "hover" | "scroll";
type EventHandlers = {
[K in EventType as `on${Capitalize<K>}`]: (type: K) => void;
};
// Result:
// {
// onClick: (type: "click") => void;
// onHover: (type: "hover") => void;
// onScroll: (type: "scroll") => void;
// }
Here, the union values appear in the function parameter types, not as keys.
When This Matters
Use this technique when building state machines, event systems, or type-safe enums where each property corresponds to handling one variant of a union, but you need that variant's literal type preserved in the value position for narrowing and safety.
Key takeaway: Mapped types can transform unions into property values by using as clauses for keys and placing the union member in function parameters, return types, or nested structures — giving you type safety across both sides of the key-value pair.