Mapped types

Advanced · 10 min

Building an object type by looping over keys: T[K] for property types, adding and removing readonly and ?, modifier preservation, and key remapping with as.

Before thisUtility types for objectsIndexed access typesThe keyof and typeof type operatorsWhy generics, and generic functions

Jack Herrington · 10 min

Mapped types

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Jack HerringtonReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A mapped type `{ [K in Keys]: X }` builds an object type by producing one property per member of the union `Keys`, which keeps a derived type in step with its source.
  • Inside the mapping, `T[K]` refers to the original property's type, so `{ [K in keyof T]: T[K] }` is a copy of `T` that each variation can then change.
  • `readonly` and `?` can be added to every property, and prefixing them with `-`, as in `-readonly` and `-?`, removes them; `-?` also strips `undefined` from the property type, as `Required` does.
  • A homomorphic mapped type, one that maps over `keyof T`, copies each property's `readonly` and `?` from `T`; mapping over a plain union of keys, as `Record` does, starts with no modifiers.
  • An `as` clause remaps each key, often with a template literal type such as `` `get${Capitalize<string & K>}` ``, and remapping a key to `never` removes that property.
  • `Partial`, `Required`, `Readonly`, `Pick` and `Record` are all short mapped types in the standard library.

The problem the utilities didn’t solve

Partial and Readonly cover common reshapes. Sooner or later you need one the standard library doesn’t have. Say your app has feature flags:

interface FeatureFlags {
  darkMode: boolean;
  betaSearch: boolean;
  newCheckout: boolean;
}

A settings screen lets an admin override each flag as on, off, or “use the default.” You need the same keys with a different value type. Writing a second interface by hand means it drifts the moment someone adds a flag.

A mapped type is a loop over keys that produces an object type. Think of it as Array.prototype.map, but the array is a union of key names and the output is one property per key:

type FlagOverrides = { [K in keyof FeatureFlags]: boolean | "default" };
// { darkMode: boolean | "default"; betaSearch: ...; newCheckout: ... }

[K in keyof FeatureFlags] means “for each key K in this union.” Add a flag to the interface and FlagOverrides grows with it.

Using the original type: T[K]

Inside the loop, K is the current key, so T[K] is the original property’s type. Made generic, that gives you reusable transformations:

type MyPartial<T> = { [K in keyof T]?: T[K] };
type Getters<T> = { [K in keyof T]: () => T[K] };
type Nullable<T> = { [K in keyof T]: T[K] | null };

const flagGetters: Getters<FeatureFlags> = {
  darkMode: () => true,
  betaSearch: () => false,
  newCheckout: () => false,
};

MyPartial is character for character how the standard library defines Partial. The object utilities aren’t special; they’re mapped types you’ve been using without seeing the loop.

Adding and removing modifiers

Two modifiers can appear in a mapping: readonly before the key and ? after it. Writing them adds them to every property. Prefixing them with - takes them away (a + prefix also exists and means the same as writing the modifier alone):

type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Concrete<T> = { [K in keyof T]-?: T[K] };

interface Draft {
  readonly id: string;
  title?: string;
}

const editable: Mutable<Draft> = { id: "d1" };
editable.id = "d2"; // fine: readonly was removed

const complete: Concrete<Draft> = { id: "d1" }; // Error: property 'title' is missing
const blank: Concrete<Draft> = { id: "d1", title: undefined }; // Error: undefined is not assignable to string

Concrete is how Required works, and the second error shows a detail of -?: it removes the undefined that optionality added, not just the question mark. There is no built-in Mutable, which is why the -readonly version above turns up in many codebases. Use it carefully, since it undoes a promise someone made on purpose.

Homomorphic mapped types keep modifiers

Look again at Mutable<Draft>. Only readonly was removed, yet title stayed optional, even though the mapping never mentioned ?. That’s because mapping over keyof T makes a homomorphic mapped type, one with the same shape as T. TypeScript copies each property’s readonly and ? from T unless you say otherwise.

Mapping over a plain union of keys has no source to copy from:

type DraftGetters = Getters<Draft>; // { readonly id: () => string; title?: () => string | undefined }

type DraftStrings = Record<keyof Draft, string>; // { id: string; title: string }
const strings: DraftStrings = { id: "d1" }; // Error: property 'title' is missing
strings.id = "d2"; // fine: no readonly either

Record<K, V> is defined as { [P in K]: V }, where K is just a union of keys. Even though the union is keyof Draft, the mapping isn’t tied to Draft, so the properties start plain. Pick is homomorphic because its K is constrained to keyof T, so it does keep modifiers. When a derived type quietly loses readonly, this is usually why. Homomorphic mapped types also preserve arrays and tuples: applying Nullable to a tuple gives a tuple, not an object with numeric keys.

Remapping keys with as

Since TypeScript 4.1, an as clause can rename each key as it passes through. Combined with a template literal type, that produces real getter names:

type GetterMethods<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};

type FlagApi = GetterMethods<FeatureFlags>;
// { getDarkMode: () => boolean; getBetaSearch: ...; getNewCheckout: ... }

string & K keeps only string keys, for the reason covered in keyof and typeof: keyof T can include number and symbol, and Capitalize only accepts strings.

Remapping a key to never removes it, which turns the as clause into a filter. Here, with a conditional type deciding each key:

interface Account {
  id: string;
  balance: number;
  deposit(amount: number): void;
  close(): void;
}

type DataOnly<T> = {
  [K in keyof T as T[K] extends Function ? never : K]: T[K];
};

type AccountData = DataOnly<Account>; // { id: string; balance: number }

About the video

Jack Herrington’s “No BS TS” episode builds mapped types up from keyof, then moves on to key remapping with template literal types and Capitalize, and finishes with optional modifiers, so it lines up with most of this lesson in under ten minutes. It doesn’t show removing modifiers with -readonly and -? explicitly, and it doesn’t name the homomorphic behaviour, which is why those sections above go into detail. The Typed Rocks video below refactors a hand-written type into a mapped type step by step, and basarat’s covers as clauses on their own.

Check yourself

  1. 01How would you write `Partial<T>` yourself?

    `type MyPartial<T> = { [K in keyof T]?: T[K] };`. It loops over every key of `T`, keeps each property's original type with `T[K]`, and adds the `?` modifier to each one.

  2. 02What is the difference between `{ [K in keyof T]: T[K] }` with a `-readonly` prefix and one with a `-?` suffix?

    `-readonly [K in keyof T]` removes `readonly` from every property, making the result mutable. `[K in keyof T]-?` removes optionality, making every property required and stripping `undefined` from the types of the formerly optional ones.

  3. 03Given `interface Draft { readonly id: string; title?: string }`, why does `{ [K in keyof Draft]: () => Draft[K] }` keep `id` readonly while `Record<keyof Draft, string>` doesn't?

    The first maps over `keyof Draft` directly, which makes it homomorphic, so TypeScript copies each property's modifiers from `Draft`. `Record` maps over its own type parameter `K`, which isn't tied to any source type, so the properties it produces start plain: `id` is mutable and `title` is required.

  4. 04Why does a getter-generating mapped type use `Capitalize<string & K>` rather than `Capitalize<K>`?

    `keyof T` can contain `number` and `symbol` keys, but `Capitalize` and template literal types only work on strings. Intersecting with `string` keeps just the string keys, so the template is valid for any `T`.

  5. 05How can a mapped type keep only the properties of `T` whose values are functions?

    Use an `as` clause that maps unwanted keys to `never`: `{ [K in keyof T as T[K] extends Function ? K : never]: T[K] }`. A key remapped to `never` is dropped from the result.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark