sajad torkamani

In a nutshell

A mapped type is a generic type that uses a union of property keys (usually created via the keyof operator) to iterate through keys to create a new type.

Mapped types are useful for creating a new type that uses the properties of another type. As an example, suppose you had the following FeatureConfig type where each property is a function:

type FeatureConfig = {
  darkMode: () => void;
  betaDashboard: () => void;
}

// Maybe you use the FeatureConfig type as an argument:
// function configure(config: FeatureConfig) {}

You can use mapped types to create a new type that uses the same properties but where the types of the properties are booleans instead:

type FeatureConfig = {  
  darkMode: () => void;
  betaDashboard: () => void;
}

type ConfigFlags<Type> = {
  [Property in keyof Type]: number
}

type FeatureFlags = ConfigFlags<FeatureConfig>
// FeatureFlags is now equal to { darkMode: number; betaDashboard: number }

To create a mapped type then, you typically:

  1. Accept a generic type (e.g., MyNewType<Type> = {...}
  2. Use something like [Property in keyof Type]: <new-type> to create new types based on the keys of the generic type.

See an example of mapped types here.

Sources