What is an Immediately Indexed Mapped Type (IIMT)?
mainAn Immediately Indexed Mapped Type (IIMT) is a TypeScript pattern used to transform a union or an object's keys into a new union of objects.
It works in two steps:
- Create a mapped type: Iterate over a set of keys or a union to create a temporary object type where each key maps to a new structure.
- Immediately index: Use the original keys/union to index into that mapped type, which collapses the object into a union of its values.
This pattern is highly effective for creating discriminated unions where you need to preserve context from the original union (like the specific member being iterated) within the new object structure.
type SomeObject = {
a: string;
b: number;
};
// The IIMT pattern
export type Example = {
[K in keyof SomeObject]: {
key: K;
};
}[keyof SomeObject];
// Resulting type:
// | { key: 'a' } | { key: 'b' }