Learning navigation

Code with Animation

Mapped Types

Looping over keys to generate new object types.

TypeScript5 min readConcept 30 of 54

The Type-Level Map

In JavaScript, you use .map() to loop over an array and transform its values.

In TypeScript, a Mapped Type loops over a union of string keys (usually from keyof) to generate a brand new object type.

Don't Duplicate Types

If you have a User type, and you need a new type for the "Edit Profile" form where every field is optional, you shouldn't create a PartialUser type by copy-pasting and adding ? everywhere.

Instead, you use a mapped type to dynamically loop over the original User keys and append the ? modifier automatically.

Syntax

type User = { id: number; name: string };

// Loop over every key in T. Add the `?` modifier.
// The value type is extracted using T[K] (Indexed Access).
type MyPartial<T> = {
  [K in keyof T]?: T[K];
};

type PartialUser = MyPartial<User>;
// Result:
// {
//   id?: number;
//   name?: string;
// }

Try it

Toggle the mapping modifiers and watch how the [K in keyof T] loop iterates over the original User interface, applying the modifications to every single property.

Apply Modifier:
type User = {
  id: number;
  name?: string;
};
type MyMapped<T> = {
[K in keyof T]: T[K];
};
type Result = MyMapped<User>;
Mapped Type Output
Result
{
readonlyid?: number;
readonlyname?: string;
}

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What does the mapped type `type Booleans<T> = { [K in keyof T]: boolean }` do?

Remember this

  • Mapped types use the syntax [K in keyof T]: Type.
  • They act like a loop, iterating over each key to construct a new object type.
  • You can add modifiers during the loop by adding readonly or ?.
  • You can strip modifiers during the loop by prefixing them with a minus sign (-readonly or -?).

Done with this concept?

Mark it complete to track your progress. No login needed.