Level up your TypeScript with Mapped Types!

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:

  1. We define an interface User with properties name and age.
  2. We define a mapped type named ReadonlyUser. This type takes a generic type T and creates a new type with all properties of T marked as readonly.

[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.

  1. We create a variable user of type User.
  2. We use the ReadonlyUser mapped type to create a new type ReadonlyUser<User>. This creates a new type with the same properties as User but marked as read-only.
  3. We assign the user object to a variable readonlyUser of type ReadonlyUser<User>.
  4. Trying to modify the name property of readonlyUser will result in an error because it's 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

要查看或添加评论,请登录

Shoaib Ahmed Khan的更多文章

社区洞察

其他会员也浏览了