Mapped types in TypeScript are a powerful feature within the type system that allows you to transform one type into another by mapping over the properties of an existing type. This transformation can involve adding, removing, or modifying the modifiers (e.g., readonly, ? for optional) of the properties, or even changing the types of the properties themselves in a structured way.
Basic Syntax
The basic syntax for mapped types looks something like this:
type MappedType<T> = {
[P in keyof T]: // 'P' is a type parameter that iterates over each property in T
// Transformation logic here, e.g., making all properties readonly
readonly T[P] // Example transformation: making each property readonly
}
keyof T returns a type that represents all property names of T as a union of string literals.
[P in keyof T] is a mapped type iterating over each property P in T.
T[P] accesses the type of the property P in T.
Examples
1. Making All Properties Readonly
type MakeReadonly<T> = {
readonly [P in keyof T]: T[P]
}
interface Original {
name: string;
age: number;
}
type ReadonlyOriginal = MakeReadonly<Original>;
// Attempting to modify a property will result in a TypeScript error
const obj: ReadonlyOriginal = { name: 'John', age: 30 };
// obj.name = 'Jane'; // Error: Cannot assign to 'name' because it is a read-only property.
2. Making All Properties Optional
type MakeOptional<T> = {
[P in keyof T]?: T[P]
}
interface Original {
name: string;
age: number;
}
type OptionalOriginal = MakeOptional<Original>;
const obj: OptionalOriginal = {}; // No error, all properties are optional
3. Making All Properties Nullable
type MakeNullable<T> = {
[P in keyof T]: T[P] | null
}
interface Original {
name: string;
age: number;
}
type NullableOriginal = MakeNullable<Original>;
const obj: NullableOriginal = { name: null, age: 30 }; // Valid
4. Pick and Omit as Mapped Types
While not always recognized as such, TypeScript's built-in Pick and Omit utilities are essentially predefined mapped types:
type Pick<T, K extends keyof T> = {
[P in K]: T[P]
}
- `Omit<T, K>`: Constructs a type by picking all properties from `T` and then removing properties `K`.
```typescript
type Omit<T, K extends keyof T> = {
[P in keyof T as P extends K ? never : P]: T[P]
}
Note the use of the as clause in Omit, which is a feature of mapped types that allows for more complex property name transformations, including filtering out properties.
5. Using the as Clause for Property Name Transformation
The as clause allows for more advanced transformations, such as renaming properties. Here’s an example of a mapped type that prefixes all property names with readonly_:
type PrefixReadonly<T> = {
[P in keyof T as `readonly_${P}`]: T[P]
}
interface Original {
name: string;
age: number;
}
type PrefixedOriginal = PrefixReadonly<Original>;
const obj: PrefixedOriginal = {
readonly_name: 'John',
readonly_age: 30,
};
Conclusion
Mapped types are a versatile tool in TypeScript for creating new types based on existing ones, enabling a wide range of type transformations that support robust and expressive type modeling. By understanding and leveraging mapped types, developers can write more type-safe, maintainable, and self-documenting code.