TS Mapped Types

TypeScript Mapped Types

Mapped types act perfectly as a "for loop" for the TypeScript type system.

They allow you to create completely new types by transforming the properties of an existing type.

This avoids duplicating code when you need variations of the same data structure.

It is the exact technology used under the hood for utilities like Partial and Readonly.


1. Syntax of a Mapped Type

A mapped type uses the [K in Keys] syntax to iterate over a union of keys.

The in keyword tells the compiler to loop over each key and apply a new typing rule.

This is incredibly powerful when combined with the keyof operator to grab properties dynamically.

It ensures that any structural changes to the base type cascade automatically.

Basic Mapped Type Example:

type OptionsFlags<Type> = {
  // Iterate over every key and turn its value into a boolean
  [Property in keyof Type]: boolean;
};

type Features = { darkMode: () => void; newUI: string };

// Both properties are now strictly forced to be booleans! type FeatureOptions = OptionsFlags<Features>;


2. Adding and Removing Modifiers

Mapped types let you easily add or subtract property modifiers like readonly and ?.

To completely remove a modifier, you simply prefix it with a minus sign (-).

For instance, -readonly strips immutability, and -? makes optional fields strictly required.

This gives you microscopic control over how data is mutated across your application.

Modifier Example:

// Removes the 'optional' modifier from all properties
type MakeRequired<Type> = {
  [Property in keyof Type]-?: Type[Property];
};

type Draft = { title?: string; id?: number }; type Final = MakeRequired<Draft>; // Now required!


3. SEO and Data Transformation

Mapped types ensure front-end view models perfectly sync with your backend database schemas.

By mapping DTOs (Data Transfer Objects), you ensure components render without unexpected missing fields.

Properly rendered components eliminate layout shifts, strongly improving SEO Page Experience scores.

Your application becomes far more resilient to structural data changes.

Readonly Mapping Example:

type ImmutableModel<T> = {
  readonly [K in keyof T]: T[K];
};

// Protects objects from accidental reassignment


Exercise

?

How do you explicitly remove an optional modifier in a mapped type?


4. Final Thoughts

Mapped types let you manipulate the entire structure of objects dynamically and elegantly.

They represent the pinnacle of writing highly adaptable, reusable type logic.

Next, we'll dive deep into understanding TypeScript's internal Type Inference!