Skip to content
Tutorials Center
My learning

Topics

Lesson 43 of 96 ยท Type Manipulation

Mapped Types

Learn TypeScript mapped types - loop over keys with K in keyof T, add or remove readonly and ?, rename and filter keys with as, and build your own utilities.

In the previous lesson you used Partial, Readonly, Pick and Record as black boxes. Every one of them is a mapped type: a type that walks over a set of keys and produces a property for each one. It is the type-level version of a for loop that builds an object.

Once you can write mapped types yourself, you're no longer limited to the built-in utilities. You can turn a settings interface into a form-state type, generate getName()/getEmail() method signatures from property names, keep only the properties of a certain type, or describe a handler for every event in an event map. The compiler keeps all of these in sync with the original type automatically.

This lesson builds on keyof, typeof and indexed access types: you'll use keyof T to get the keys and T[K] to read each property's type. It also reuses the Expect/Equal compile-time check from the utility types lesson: if an example compiles and prints its last line, every Expect passed.

The basic syntax

A mapped type looks like an index signature with in instead of a colon:

TypeScript
type Flags = { [K in 'darkMode' | 'beta' | 'offline']: boolean };
// { darkMode: boolean; beta: boolean; offline: boolean }

Read it as "for each K in this union, create a property named K of type boolean". K is a type variable that takes each member of the union in turn, just like a loop variable. You can name it anything; K (for key) and P (for property) are conventional.

The real power comes when the right-hand side uses K. Combined with keyof and indexed access, you can copy and transform an existing type:

TypeScript Mapping over keys

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

{ [K in keyof T]: () => T[K] } loops over 'volume' | 'language' | 'notifications'. For K = 'volume', T[K] is number, so the property becomes volume: () => number, and so on. If you add a property to Settings, the getters object stops compiling until you add a getter for it. That's the point: the derived type can never fall out of step.

Building the built-in utilities yourself

Several utilities from the previous lesson are one-line mapped types. Writing them yourself is the best way to understand both:

TypeScript Your own Partial, Readonly, Pick and Record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Some details:

  • MyPartial puts ? after the brackets, MyReadonly puts readonly before them. Those are the two modifiers a mapped type can add.
  • MyPick doesn't loop over keyof T but over Keys, a subset of it. The constraint Keys extends keyof T is what makes T[K] legal, and it's why Pick rejects unknown keys.
  • MyRecord loops over any union of keys. PropertyKey is a built-in alias for string | number | symbol, the types that can be object keys.

These match the real definitions in TypeScript's standard library almost character for character.

Adding and removing modifiers

You can also remove modifiers by prefixing them with -. A + prefix (adding) is allowed too, but it's the default, so you'll rarely see it.

Syntax Effect on each property
readonly [K in keyof T] or +readonly add readonly
-readonly [K in keyof T] remove readonly
[K in keyof T]? or +? make optional
[K in keyof T]-? make required

Required<T> is { [K in keyof T]-?: T[K] }. There's no built-in for removing readonly, but it's a common need when you build an object step by step and freeze it afterward:

TypeScript Removing readonly and ? with minus

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Notice how -? turned timeout?: number into timeout: number, not timeout: number | undefined. Removing the question mark also removes the undefined that optionality added. (With exactOptionalPropertyTypes, explained in the strict mode lesson, optional properties don't add undefined in the first place.)

Homomorphic mapped types keep modifiers

A mapped type of the form { [K in keyof T]: ... } is called homomorphic ("same shape"): it maps over the keys of an existing type. Homomorphic mapped types copy the modifiers of the original properties unless you change them. That's why Getters<T> above would keep a readonly or ? that Settings had, and why Mutable<Config> kept timeout optional.

They have a second useful property: when T is an array or tuple type, the result is an array or tuple too, not an object with keys like length and push:

TypeScript Mapping over tuples

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The as Boxed<T> assertion is needed because Array.prototype.map returns a plain array type; TypeScript can't prove that mapping a tuple at runtime matches the mapped tuple type. Keeping such assertions inside one small, well-tested helper is a reasonable trade-off (see type assertions).

Key remapping with as

Since TypeScript 4.1, a mapped type can rename each key with an as clause. The expression after as is a type that computes the new key from K. Template literal types are a natural fit for building new names:

TypeScript Generating getter names with as

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Two pieces need a word of explanation:

  • `get${...}` is a template literal type: it builds a string literal type such as 'getName'.
  • Capitalize only accepts string types, but keyof T may include number or symbol keys. string & K intersects the key with string, which keeps string keys and turns other keys into never. Without it, you'd get error TS2344: "Type 'K' does not satisfy the constraint 'string'."

Filtering keys

If the as clause produces never, that key is dropped. Combined with a conditional type, this lets you filter properties by name or by value type:

TypeScript Keeping only properties of a given type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

T[K] extends V ? K : never asks, for each key, "is this property's type assignable to V?" Keys that answer no become never and disappear. Passing the full account to sumNumbers works because of structural typing: an object with extra properties is still a valid Numbers when it's not a fresh object literal.

A pitfall: optional properties add undefined

An older way to collect "the keys whose values are numbers" maps every property to its key or never and then indexes the result with [keyof T] to turn it into a union. It looks right, but optional properties sneak in an undefined:

TypeScript The undefined that sneaks in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

You'd expect KeysOfType<Contact, number> to be 'id' | 'age', but the first check proves it is 'id' | 'age' | undefined, and the program happily stores undefined in a variable that was supposed to hold a key. The cause: the mapped type is homomorphic, so it kept email's ?, and reading an optional property with [keyof T] adds undefined. StrictKeysOfType adds -?, so no property in the intermediate object is optional and the result is exactly 'id' | 'age'. Try changing the type of key to StrictKeysOfType<Contact, number>: the program then fails with error TS2322.

When you only need the filtered object rather than a union of keys, prefer the as clause from PickByValue: it removes keys instead of mapping them to never, so this problem doesn't arise.

Mapping a union of event names

Mapped types don't have to start from an object type. A common pattern turns an event map (event names to payload types) into a matching set of handler types, which is the heart of a type-safe event emitter (you'll build a full one in the event system project):

TypeScript Handlers derived from an event map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Inside handlers, the parameters payload and { from, text } need no annotations: contextual typing gives each handler the payload type of its event. A typo such as onLogn or a handler that reads payload.user would not compile. The dispatch function needs two assertions because the event name is computed at runtime; the public API, dispatch('login', { userId: 42 }), stays fully checked.

Simplify: flattening intersections

When you combine types with &, editors display the intersection as written, for example Pick<User, 'id'> & Partial<Omit<User, 'id'>>. That's hard to read, and the strict Equal check treats an intersection as different from the equivalent flat object. An identity mapped type fixes both:

TypeScript
type Simplify<T> = { [K in keyof T]: T[K] };

type Update = Simplify<Pick<User, 'id'> & Partial<Omit<User, 'id'>>>;
// shown as { id: number; name?: string; email?: string }

Mapping over keyof (A & B) visits every key of both sides, and the result is a single object type. Many codebases call this helper Prettify. It changes only how the type is displayed and compared, never which values are allowed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is { [K in 'a' | 'b']: K }?

    K takes each member of the union in turn and is also used as the property's type, so each property's type is its own name as a literal type.
  2. 2. Which mapped type turns { readonly id: number; note?: string } into { id: number; note?: string }?

    The minus prefix removes readonly. The mapped type is homomorphic, so the ? on note is preserved. A plain copy would keep readonly too.
  3. 3. What happens to a key when the as clause of a mapped type evaluates to never?

    Remapping a key to never drops it, which is how you filter properties by name or by value type.
  4. 4. Why does Capitalize<string & K> need the string & part?

    string & K keeps string keys and turns number or symbol keys into never, satisfying Capitalize's string constraint.
  5. 5. For type Boxed<T> = { [K in keyof T]: { value: T[K] } }, what is Boxed<[number, string]>?

    Homomorphic mapped types applied to a tuple or array type produce a tuple or array, mapping only the elements.

Summary

  • A mapped type { [K in Keys]: Type } creates one property per member of the key union; K works like a loop variable.
  • { [K in keyof T]: T[K] } copies a type; change the right-hand side to transform every property's type.
  • Add modifiers with readonly and ?, remove them with -readonly and -?. -? also removes the undefined that optionality added.
  • Homomorphic mapped types (over keyof T) keep the original modifiers and map arrays and tuples element by element.
  • as renames keys (often with template literal types like `get${Capitalize<string & K>}`); mapping a key to never filters it out.
  • Partial, Required, Readonly, Pick and Record are all one-line mapped types, and Simplify<T> flattens intersections for display and comparison.

Next: Conditional Types