Level up your TypeScript with Mapped Types!
In the Article i will try to explain a lesser-known concept mapped types in an easy-to-understand way. Let's unlock the full potential of TypeScript together!
Here's the code snippet:
interface User {
name: string;
age: number;
}
// Define a mapped type to create a ReadonlyUser type
type ReadonlyUser<T> = {
readonly [P in keyof T]: T[P];
};
const user: User = { name: "Alice", age: 30 };
// Now user cannot be modified because it's ReadonlyUser
const readonlyUser: ReadonlyUser<User> = user;
// readonlyUser.name = "Bob"; // Error: cannot reassign a readonly property
Explanation:
[P in keyof T]: This syntax iterates over all the keys of the generic type T.
T[P]: This accesses the type of the property with key P from T.
readonly: This keyword makes the property read-only.
Mapped types are a powerful feature in TypeScript that allows to manipulate the structure of other types. This example demonstrates how to create a read-only version of an existing interface.
#TypeScript #MappedTypes #DeveloperCommunity