Mapped Types
What
Mapped types allow you to create a new object type by iterating over the keys of an existing type.
How
You use the keyof operator to get the keys and the in keyword to loop through them:
type Soldier = { name: string; age: number; };
type ReadonlySoldier = {
readonly [K in keyof Soldier]: Soldier[K];
};
Why
Mapped types are ideal for mass-modifying properties. Instead of manually creating Optional or Readonly versions of every interface, you can write a single mapped type that transforms any input type. This ensures that if the base type is ever updated, all your mapped variations are automatically updated as well.
Summary
Use mapped types to transform entire object structures in a clean, maintainable way.