Mapped types are a powerful feature in TypeScript that allow you to create new types based on existing ones. They provide a way to transform properties of an existing type, creating a new type with modified characteristics.
At its core, a mapped type is a generic type which uses a union of PropertyKeys (frequently created via a keyof operator) to iterate through keys and create a new type.
type MappedType<T> = {
[P in keyof T]: T[P];
}
This syntax creates a new type by iterating over each property (P) in the original type (T).
type Partial<T> = {
[P in keyof T]?: T[P];
}
type Readonly<T> = {
readonly [P in keyof T]: T[P];
}
Mapped types can be combined with other TypeScript features for more complex transformations:
type NonNullable<T> = {
[P in keyof T]: T[P] extends null | undefined ? never : T[P];
}
This example uses conditional types to remove null and undefined from property types.
Mapped types are a cornerstone of TypeScript's type system, enabling developers to create flexible and reusable type transformations. By mastering mapped types, you can write more maintainable and type-safe code.
For more advanced type manipulations, explore conditional types and utility types in TypeScript.