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:

typescript
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`:

typescript
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:

typescript
type ReadonlyType<T> = {
  readonly [P in keyof T]: T[P];
};

// Usage:
type ReadonlyUser = ReadonlyType<User>;

Let's break down this syntax: - `` means our mapped type works with any type `T`. - `keyof T` generates a union of all keys in `T` (like `"id" | "name" | "age"`). - `[P in keyof T]` loops over each key `P`. - `readonly` adds the readonly modifier to each key. - `T[P]` specifies the type of each property.

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` makes all properties optional. - `Readonly` makes all properties readonly. - `Required` makes all optional properties required. - `Record` constructs a type with keys of type `K` and values of type `T`.

Experiment with mapped types to make your code cleaner and safer. Happy coding!