Skip to main content

Front-End Development

TypeScript Type Manipulation with keyof, typeof, and Mapped Types

Istock 1138332540

TypeScript offers powerful type manipulation capabilities that allow developers to create more flexible and maintainable code. Three key features that enable this are keyof, typeof, and Mapped Types. Let’s explore each of them with examples.

keyof: The keyof operator takes an object type and produces a string or numeric literal union of its keys.

Example:

Picture1

This is useful for creating dynamic and type-safe property accessors:

Picture2

Here, TypeScript ensures that key must be a valid property of User.

typeof: Inferring Types from Values

The typeof operator allows us to extract the type of a variable or property.

Example:

Picture3

Now, UserType will have the same structure as user, which is useful when working with dynamically created objects.

Another use case is inferring function return types:

Picture4

Mapped Types: Transforming Types Dynamically

Mapped Types allow you to create new types based on existing ones by iterating over keys.

Example: Making Properties Optional

Picture5

Now, PartialUser has all properties of User, but they are optional.

Example: Making Properties Readonly

Picture6

Now, ReadonlyUser prevents any modification to its properties.

Example: Creating a Record Type

Picture7

Here, UserPermissions will be an object with keys from UserRoles and boolean values:

Picture8

Conclusion

By leveraging keyof, typeof, and Mapped Types, TypeScript allows developers to write more flexible and type-safe code. These advanced features help in dynamically generating types, ensuring correctness, and reducing redundancy in type definitions.

Thoughts on “TypeScript Type Manipulation with keyof, typeof, and Mapped Types”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Anchal Katoch

Anchal Katoch is a Technical Consultant at Perficient. She is a front-end developer with experience in working with Sitecore from about 4+ years. She loves technology and hence is curious to learn about new emerging technologies.

More from this Author

Follow Us