How to Use Mapped Types in TypeScript

Updated: January 8, 2024 By: Guest Contributor Post a comment

Introduction

Embrace the power of TypeScript to transform properties within your typescripts with ease; Mapped Types are the sorcery to know.

Mapped Types Basics

Mapped types in TypeScript allow you to take an existing model and transform its properties in various ways. Imagine a spell that changes the nature of objects—not their essence, but their qualities, turning leaden arrays into golden compilations of readonly alternatives or optional nuggets.

type ReadOnly = {
  readonly [P in keyof T]: T[P];
};

With this spell, you can create an immutable version of an object, preventing the rough hands of time and imprudence from altering its content.

Partial Types

Often in the winding river of coding, we wish to make some properties optional. The ‘Partial’ type allows every property of a given type to be optional.

type Partial = {
  [P in keyof T]?: T[P];
};

Now you have the liberty like rivers breaking banks, to pick and choose what you’ll provide.

Pick Types

Rather like opting for select fishes from the Mississippi than hauling up every living creature, the ‘Pick’ type allows choosing certain properties from an object.

type Pick<T, K extends keyof T> = {
  [P in K]: T[P];
};

This targeted selectiveness leads to an object that holds just the properties you deemed worthy to bear.

Record Types

Dictating the structure just as one might dictate a letter, the ‘Record’ type lets you define the type of keys and values in an object.

type Record = {
  [P in K]: T;
};

You declare the homogeneity of the values cast across the keys you have penned down.

Conditionally Applying Mapped Types

Using conditional types with mapped types is much like navigating the mighty Mississippi—predicaments may alter your path. Here we can target certain properties for mapping.

type ConditionalMap = {
  [P in keyof T]: T[P] extends Function ? P : never;
};

type FunctionProperties = ConditionalMap[keyof T];

We can fish out exactly what the situation demands—the functional aspects from the dross.

Utility Types and Beyond

TypeScript’s utility types avail themselves like a steamboat ready to ease your journey. Explore beyond the basics; tread into ‘Exclude’, ‘Extract’, ‘ReturnType’, and such, each altering the course of your types as needed.

Conclusion

As Mark Twain found marvels along the Mississippi, so can you marvel at the beguiling simplicity TypeScript’s Mapped Types present, charting the undefined wilderness of coding specificity. Armed with these spells, triumph in creating flexible and maintainable code.