Mastering Mapped Types in TypeScript for Efficient Code

Stop duplicating your types. Let TypeScript write them for you! In my last post, I talked about the 'Template Literal Types,' and how they allow us to construct new string literal types by combining existing ones. Another powerful feature that builds on similar ideas but operates at the object level is 'Mapped Type.' Mapped types allow you to create new types by transforming existing ones. Instead of manually redefining similar structures again and again, you describe how each property should change, and TypeScript does the rest for you. If you’ve used the 'map' function in JavaScript to transform arrays, the idea here is very similar. Instead of iterating over array values, a mapped type iterates over property keys and produces a new object type. Under the hood, mapped types are built on concepts you may already know, such as index signatures and the 'keyof' operator. While index signatures let you describe properties that are not known ahead of time, mapped types let you take a known set of keys and systematically transform them into something new. If a property is added, removed, or modified in the original type, all mapped types update automatically. There is no duplication and no risk of forgetting to update something later. One important detail is that mapped types are not limited to 'keyof' an existing object. Any union of values that can be used as object keys can be mapped over. This means you can generate object types from string unions, number unions, or symbol unions. However, the key must ultimately be assignable to string, number, or symbol, because those are the only valid property key types in JavaScript. You might wonder whether a 'Record' type could be used instead of a mapped type in these scenarios. While Record is useful when all properties share the same value type, it falls short when the value type needs to vary depending on the key. Mapped types shine precisely because they allow that key-dependent transformation. Mapped types are the foundation for many built-in TypeScript utilities such as 'Partial', 'Readonly', 'Pick', and 'Omit.' Once you understand how mapped types work, those utility types stop feeling magical and start feeling obvious. In many ways, mapped types are where TypeScript transitions from being a typing tool to being a type-level programming language. #TypeScript #JavaScript #Programming #Coding #WebDevelopment

  • text

To view or add a comment, sign in

Explore content categories