🔷 TypeScript Intermediate

What are mapped types in TypeScript?

Answer

Mapped types create new types by transforming all properties of an existing type using the [K in keyof T] syntax. They iterate over each key of type T and produce a new property. Basic example: type Optional<T> = { [K in keyof T]?: T[K] }; — makes all properties optional (same as Partial<T>). Making all properties readonly: type Frozen<T> = { readonly [K in keyof T]: T[K] };. Nullify all values: type Nullable<T> = { [K in keyof T]: T[K] | null };. Modifiers: use + or - to add or remove modifiers — -readonly removes readonly, -? removes optionality. Key remapping (TS 4.1): type Getters<T> = { [K in keyof T as `get\${Capitalize<string & K>}`]: () => T[K] }; — generates getter method types. Mapped types are the foundation of most built-in utility types (Partial, Required, Readonly, Record, Pick, Omit) and enable powerful type transformations.