A cool trick to write better TypeScript code is to use mapped types.
What is Mapped types
Mapped types allow you to create new types by transforming properties of existing types, making your code more flexible, and less prone to errors. Let’s take a look at an example:
Suppose you have a type representing a User:
|
|
Now, you want to create a new type with optional properties based on the User
type. You can use a mapped type to achieve this:
|
|
OptionalUser
will now have the same properties as User
, but all of them will be optional:
|
|
You can even go further and create a utility type to make any property of a given type readonly:
|
|
Now you have a ReadonlyUser type where all properties are immutable:
|
|
Mapped types can help you create more versatile and maintainable TypeScript code by reducing duplication and allowing for easy transformation of existing types.
P.S. Can you identify the TypeScript utility type that actually accomplishes this? (Special thanks to my coworker @thomasnotfound for bringing this to my attention.) Cheer! 🍺