Mastering TypeScript Mapped Types for Cleaner Code
Learn how to use TypeScript mapped types to write cleaner, more flexible, and reusable code with practical examples.
TypeScript is a powerful language that enhances JavaScript with static typing. One of its most useful features is mapped types, which help you transform types efficiently and keep your code DRY (Don't Repeat Yourself). If you're new to mapped types, this article will guide you through the basics with clear examples.
Mapped types allow you to create new types by taking existing ones and applying transformations to their properties. This is especially helpful when you want to create variations of a type, like making all properties optional or readonly, without rewriting the entire type.
Here's a simple example. Suppose you have a type representing a user:
type User = {
id: number;
name: string;
age: number;
};Now, imagine you want a version of this type where all properties are optional, for example, when updating a user. Instead of manually setting all properties as optional, you can use the built-in mapped type `Partial`:
type PartialUser = Partial<User>;
// Equivalent to:
// type PartialUser = {
// id?: number;
// name?: string;
// age?: number;
// };The `Partial` mapped type takes every property from `User` and makes it optional by adding a `?`. This is a concise way to create flexible types.
You can also create your own mapped types! Here's how to make all properties readonly, meaning you cannot modify them after initialization:
type ReadonlyType<T> = {
readonly [P in keyof T]: T[P];
};
// Usage:
type ReadonlyUser = ReadonlyType<User>;Let's break down this syntax:
- `
Mapped types can be combined with utility types or your own to adapt to many coding needs, making your TypeScript code more maintainable and expressive.
To summarize, here are some useful built-in mapped types in TypeScript:
- `Partial
Experiment with mapped types to make your code cleaner and safer. Happy coding!