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:
This is useful for creating dynamic and type-safe property accessors:
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:
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:
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
Now, PartialUser has all properties of User, but they are optional.
Example: Making Properties Readonly
Now, ReadonlyUser prevents any modification to its properties.
Example: Creating a Record Type
Here, UserPermissions will be an object with keys from UserRoles and boolean values:
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.
“Thanks for the great info! This is exactly what I was looking for.”