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 createdProperty: The property keyOriginalType: The original typeNewPropertyType: 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 TodoTodo[Property]: This retrieves the type of each property Property from Todo