by Timur Dautov

Mapped Types in TypeScript with Examples

A mapped type is a type that transforms one type into another type by iterating over its properties. Making every property readonly is implemented by hand in Readonly. Making them optional is what Partial does.

Syntax#

type NewType = {
    [Property in keyof OriginalType]: NewPropertyType 
}
  • NewType: The new type that will be created
  • Property: The property key
  • OriginalType: The original type
  • NewPropertyType: The new type of the property

Example: Make all properties readonly#

interface Todo {
  title: string;
  completed: boolean;
}

type ReadonlyTodo = {
  readonly [Property in keyof Todo]: Todo[Property];
}
  • Property in keyof Todo: This creates a new type by iterating over all properties of Todo
  • Todo[Property]: This retrieves the type of each property Property from Todo

References#

Comments