0
0
Typescriptprogramming~5 mins

Why mapped types are needed in Typescript

Choose your learning style9 modes available
Introduction

Mapped types help create new types by transforming existing ones easily. They save time and avoid repeating similar code.

When you want to make all properties of an object type optional or readonly.
When you need to create a type that changes all property types in a consistent way.
When you want to reuse an existing type but with some modifications to its properties.
When you want to apply the same change to many properties without writing each one manually.
Syntax
Typescript
type NewType<T> = {
  [P in keyof T]: SomeTransformation<T[P]>;
};

keyof T gets all property names of type T.

The square brackets [P in keyof T] loop over each property name.

Examples
This makes all properties of T readonly.
Typescript
type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};
This makes all properties of T optional.
Typescript
type Partial<T> = {
  [P in keyof T]?: T[P];
};
This changes all properties to allow null as a value.
Typescript
type Nullable<T> = {
  [P in keyof T]: T[P] | null;
};
Sample Program

This example shows how to create a readonly version of a User type using a mapped type. It prevents changing properties after creation.

Typescript
interface User {
  id: number;
  name: string;
  email: string;
}

type ReadonlyUser = {
  readonly [P in keyof User]: User[P];
};

const user: ReadonlyUser = {
  id: 1,
  name: "Alice",
  email: "alice@example.com"
};

// user.id = 2; // Error: Cannot assign to 'id' because it is a read-only property

console.log(user);
OutputSuccess
Important Notes

Mapped types work well with generics to create flexible and reusable types.

They help keep your code DRY (Don't Repeat Yourself) by avoiding manual type rewriting.

Summary

Mapped types let you transform all properties of a type easily.

They are useful to create readonly, optional, or modified versions of existing types.

Using mapped types makes your code cleaner and easier to maintain.