Mapped types in TypeScript are a powerful feature that allows developers to create new types by transforming properties of existing types. This transformation can include modifying property modifiers, such as making properties optional or readonly. Understanding how to effectively use mapped types can lead to more maintainable and flexible code. Below, I will explain how mapped types work, provide practical examples, and highlight best practices and common mistakes.
A mapped type takes an existing type and creates a new type by iterating over its properties. The syntax involves using the `keyof` operator to get the keys of the original type and then applying transformations to those keys. The basic structure looks like this:
type MappedType = {
[K in keyof T]: Transformation;
};
One of the most common modifications is changing properties to be optional or readonly. Here’s how you can achieve that:
To create a type where all properties of an existing type are optional, you can use the following mapped type:
type Optional = {
[K in keyof T]?: T[K];
};
// Example usage
interface User {
id: number;
name: string;
email: string;
}
type OptionalUser = Optional;
// OptionalUser is now:
// {
// id?: number;
// name?: string;
// email?: string;
// }
Similarly, you can create a mapped type that makes all properties readonly:
type Readonly = {
readonly [K in keyof T]: T[K];
};
// Example usage
type ReadonlyUser = Readonly;
// ReadonlyUser is now:
// {
// readonly id: number;
// readonly name: string;
// readonly email: string;
// }
In conclusion, mapped types are a versatile tool in TypeScript that can significantly enhance type safety and code maintainability. By understanding how to modify property modifiers effectively, developers can create robust applications that are easier to work with and extend over time.