Back

Mapped Type in Typescript

Mapped types are one of the powerful features in TypeScript that allow you to create new types by transforming properties of existing types or unions. They provide a way to programmatically create types based on existing ones, which can help you reduce code duplication and enforce consistent typing.

Let’s break it down with simple examples.

What is a Mapped Type?

A mapped type takes an existing type or union and creates a new type by iterating over the keys or union members and mapping them to new properties.

Example: Mapping Over a Union Type

type MappedType = 'primary' | 'secondary' | 'default'

type ObjMappedType = {
  [Type in MappedType]: Type
}
 // output:
 type ObjMappedType = {
  primary: "primary";
  secondary: "secondary";
  default: "default";
} 

This creates a new type with keys primary, secondary, and default each assigned their own string literal value.

type Type = {
  name: string;
  surname: string;
  age: number;
  isManager: boolean;
}

type MappedType = {
  [Key in keyof Type]?: Type[Key] | null
}
// output:
type MappedType = {
  name?: string | null;
  surname?: string | null;
  age?: number | null;
  isManager?: boolean | null;
}

Why Use Mapped Types?

Reuse existing types with modifications: You don’t have to rewrite types for optional, nullable, or readonly variants.

DRY principle: Avoid repeating yourself by programmatically creating variants of types.

Type safety: Ensures consistent changes across all keys or union members.

Summary

Mapped types let you transform types by iterating over keys or union members, enabling you to create flexible and maintainable type definitions in TypeScript.

Key Points

Use [Key in keyof T] to iterate over keys of type T.

Use [Type in Union] to iterate over members of a union.

You can add modifiers like optional (?), readonly, or change the property type.

Back