Transforming Objects in TypeScript with Mapped Types
Written on
Chapter 1: Understanding Mapped Types
Recently, I delved into advanced design patterns in TypeScript, and one of the most intriguing is Mapped Types. These types offer a method to modify the attributes of an object efficiently. With TypeScript, you can make properties nullable, read-only, or optional—transforming the way you work with objects.
The Concept of Mapped Types
Mapped Types empower you to create a new type by altering each property of an existing one. By utilizing the syntax [P in keyof T], you can systematically apply transformations to each attribute in your object. Now, let’s examine some practical examples.
Making an Object Optional
One of the most beneficial applications of Mapped Types is the ability to make an entire object optional. In practice, this means that each attribute can be rendered optional using the ?: operator.
Consider the following example with a car object:
In this scenario, if we encounter an error regarding a missing attribute (like wheels), we want to make the wheels optional since they aren't strictly necessary for the object to exist. To achieve this, we can create a Mapped Type called Optional:
This mapping generates a new type that takes all keys from the given type T and renders them optional using the ?: operator. Now, we can easily modify our car type to be optional:
Now the error has vanished! When using an IDE, you’ll likely receive suggestions like car?.wheels, as the property can now be either nullish or defined.
Making a Type Read-Only
Our second example illustrates how to set attributes within a type to read-only. This ensures that attempts to alter the values of the object will result in an error since attributes like the number of wheels should remain constant.
In the snippet above, we can mistakenly change the number of wheels to 6 without any error, which is not the desired behavior. Let's establish a ReadOnly type:
By incorporating the readonly keyword, each attribute becomes immutable. Let’s see how this applies:
Now, an error occurs when we try to modify the wheels property, confirming that it is indeed read-only.
Although we’ve only scratched the surface with these two use cases, the possibilities are endless. You could make an object nullable or convert all properties to strings—your creativity (and TypeScript's capabilities) are the only limits.
I hope you found this article insightful! I genuinely enjoyed discovering this feature and am eager to share it with you. If you appreciated this content, please consider leaving a clap or following me; your support means a lot!
Chapter 2: Practical Examples of Mapped Types
Explore how to convert a response into a model object using Mapped Types in TypeScript in this informative video.
Learn how to transform a tuple into an object with practical examples in this insightful video on TypeScript challenges.