Mapped Types
Looping over keys to generate new object types.
The Type-Level Map
In JavaScript, you use .map() to loop over an array and transform its values.
In TypeScript, a Mapped Type loops over a union of string keys (usually from keyof) to generate a brand new object type.
Don't Duplicate Types
If you have a User type, and you need a new type for the "Edit Profile" form where every field is optional, you shouldn't create a PartialUser type by copy-pasting and adding ? everywhere.
Instead, you use a mapped type to dynamically loop over the original User keys and append the ? modifier automatically.
Syntax
typescript
type User = { id: number; name: string };
// Loop over every key in T. Add the ? modifier.
// The value type is extracted using T[K] (Indexed Access).
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
type PartialUser = MyPartial<User>;
// Result:
// {
// id?: number;
// name?: string;
// }
Try it
Toggle the mapping modifiers and watch how the [K in keyof T] loop iterates over the original User interface, applying the modifications to every single property.
id: number;
name?: string;
};
Check yourself
Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.
Remember this
- Mapped types use the syntax
[K in keyof T]: Type. - They act like a loop, iterating over each key to construct a new object type.
- You can add modifiers during the loop by adding
readonlyor?. - You can strip modifiers during the loop by prefixing them with a minus sign (
-readonlyor-?).
Done with this concept?
Mark it complete to track your progress. No login needed.