Capítulo 10 de 36
A mapped type iterates every key of an existing type (usually via keyof) to produce a new type — the mechanism behind almost every built-in utility type (Partial, Required, Readonly, Pick, Record).
type OptionsFlags<Type> = { [Property in keyof Type]: boolean } — walks every key of Type and gives each one a new value type (here, boolean for all of them regardless of the original type).readonly and ?): can be added or stripped during mapping by prefixing with + (default, add) or - (remove). { -readonly [P in keyof T]: T[P] } strips readonly from every property; { [P in keyof T]-?: T[P] } strips optionality, making every property required.as (TS 4.1+): { [P in keyof T as NewKey]: T[P] } lets the mapped type rename keys as it iterates, not just retype values. Commonly combined with template literal types to derive new names (get${Capitalize<...>}), producing a "getters" version of an interface.as never in the remap clause removes it from the resulting type — the standard way to drop a specific property (e.g. via Exclude<Property, "kind"> in the as clause) while mapping the rest through unchanged.keyof output — it can be a union of any type with a suitable key expression, e.g. mapping over a union of event-object types keyed by their own kind discriminant field to build an event-name → handler config type.true/false flag type per property based on whether that property's value matches some shape.type LockedAccount = { readonly id: string; readonly name: string };
type CreateMutable<T> = { -readonly [P in keyof T]: T[P] };
type UnlockedAccount = CreateMutable<LockedAccount>; // { id: string; name: string }
readonly from every property of a type via a mapping modifier.type Getters<T> = {
[P in keyof T as `get${Capitalize<string & P>}`]: () => T[P];
};
interface Person { name: string; age: number }
type LazyPerson = Getters<Person>; // { getName: () => string; getAge: () => number }
as plus a template literal type to derive new property names from the original ones.| Modifier | Meaning |
|---|---|
[P in keyof T]: X | base mapped type |
-readonly [P in keyof T] | remove readonly from every property |
+readonly / bare readonly | add readonly (default when prefix omitted) |
[P in keyof T]-?: | remove optionality (make required) |
[P in keyof T as NewName]: | remap the key name during iteration |
as never in the as clause | drop that key from the result entirely |
T, but every property is X" — it's the general mechanism behind Partial<T>/Required<T>/Readonly<T>.as) to both rename and filter properties in one pass, instead of a separate Omit/Pick step.keyof T is the standard source for the iterated union.as clauses to derive new key names.Partial, Required, Readonly, Pick, Record are all mapped types under the hood.