Hack Frontend Community

What are Mapped Types in TypeScript

Mapped Types in TypeScript allow creating new types based on existing ones by iterating over keys and modifying them.

It's like map() for types — you can iterate over each object key and set the needed value for it.

Syntax

type NewType = {
  [Key in Union]: Type;
}
  • Key — variable name representing current key from Union set.
  • Type — value type for each key.
  • Can use keyof, modifiers (?, readonly), and utility types (Pick, Partial, etc.).

Usage Examples

Example 1: Type copy with different values

type User = {
  name: string;
  age: number;
};

// Make type where all values are boolean
type UserPermissions = {
  [K in keyof User]: boolean;
};

// => { name: boolean; age: boolean }

Example 2: All fields optional (like Partial<T>)

type Optional<T> = {
  [K in keyof T]?: T[K];
};

Usage

type User = { name: string; age: number };
type OptionalUser = Optional<User>;
// => { name?: string; age?: number }

Example 3: Make all fields readonly (like Readonly<T>)

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

Example 4: Remove readonly

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

Where Mapped Types are Used

  • When creating utility types (Partial, Pick, Readonly, Record, etc.)
  • For generating dynamic objects with predefined keys
  • For automatic type transformations based on other types
  • For type introspection in large projects (especially with GraphQL, API, Form systems)