Mapped types

Topic 4 of 6 in Type operators6 min readIntermediateFree course

Overview

Utility types like Partial and Readonly aren’t magic — they’re mapped types, a feature you can use yourself. A mapped type builds a new object type by going through the keys of another type and deciding what each property becomes. It’s like Array.map, but for the properties of a type.

The syntax

Mapped types transform every property. type Flags<T> = { [K in keyof T]: boolean }; — for each key K of T, make its type boolean. User has name: string, age: number and admin: boolean; Flags<User> has name: boolean, age: boolean and admin: boolean. Modifiers: readonly / -readonly and ? / -? add or remove flags. Rename keys with as: [K in keyof T as get${…}]. Partial, Required, Readonly and Record are all mapped types under the hood.

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

type User = { name: string; age: number; admin: boolean };
type UserFlags = Flags<User>;
// { name: boolean; age: boolean; admin: boolean }
  • [K in keyof T] loops over every key of T, calling each one K.
  • The part after the colon is the new property type.

Using the original property type: T[K]

Inside the mapping, T[K] is the type of the current property, so you can transform it rather than replace it:

TypeScript
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Getters<T> = { [K in keyof T]: () => T[K] };
type Validators<T> = { [K in keyof T]: (value: T[K]) => string | null };

type UserValidators = Validators<User>;
// {
//   name: (value: string) => string | null;
//   age: (value: number) => string | null;
//   admin: (value: boolean) => string | null;
// }

Every validator’s parameter has the exact type of the field it checks — and if someone adds a field to User, every Validators<User> object must add a validator for it.

Modifiers: readonly and ?

You can add or remove readonly and ? on every property. That’s exactly how the built-ins are written:

TypeScript
type MyPartial<T> = { [K in keyof T]?: T[K] };           // add ?
type MyRequired<T> = { [K in keyof T]-?: T[K] };         // remove ?
type MyReadonly<T> = { readonly [K in keyof T]: T[K] };  // add readonly
type Mutable<T> = { -readonly [K in keyof T]: T[K] };    // remove readonly

+ is the default (+? means the same as ?). Mapped types over keyof T preserve the original modifiers unless you change them.

Mapping over any union of keys

The thing after in can be any union of string literals, not just keyof T:

TypeScript
type Day = "mon" | "tue" | "wed";
type Schedule = { [D in Day]: string[] };
// { mon: string[]; tue: string[]; wed: string[] }

That’s how Record<K, V> is defined: { [P in K]: V }.

Renaming keys with as

Add as after the key to compute a new name. Combined with template literal types (Template literal types), this generates related property names:

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

type UserGetters = Getters<User>;
// { getName: () => string; getAge: () => number; getAdmin: () => boolean }

string & K keeps only string keys (keys can also be numbers or symbols, which Capitalize can’t handle).

Filtering keys

If as produces never, the key is dropped. With a conditional type (next lesson), you can keep only certain properties:

TypeScript
type OnlyStrings<T> = {
  [K in keyof T as T[K] extends string ? K : never]: T[K];
};

type UserText = OnlyStrings<User>;   // { name: string }

A practical example: form state

TypeScript
type FormState<T> = {
  values: T;
  touched: { [K in keyof T]?: boolean };
  errors: { [K in keyof T]?: string };
};

type SignupForm = FormState<{ email: string; password: string }>;

Form libraries such as React Hook Form use mapped types like these, which is why their APIs autocomplete your field names.

Homomorphic mapped types

A mapped type over keyof T is called homomorphic (“same shape”). Besides keeping modifiers, it has one more nice property: applied to an array or tuple type, it maps the elements and keeps it an array:

TypeScript
type Boxed<T> = { [K in keyof T]: { value: T[K] } };
type B = Boxed<[string, number]>;   // [{ value: string }, { value: number }]

You’ll rarely need that, but it explains why Readonly<string[]> gives readonly string[].

Remember: [K in Keys]: NewType builds an object type one key at a time. Use T[K] for the original type, ?/readonly (with - to remove) for modifiers, and as to rename or filter keys.

Exercise

Validators and getters from one type

Given type Signup = { email: string; age: number; terms: boolean }, write three mapped types: (1) Validators<T> — for each key, a function (value: T[K]) => string | null; (2) Errors<T> — for each key, an optional string; (3) Getters<T> — for each key k, a method named get + capitalised key (getEmail) returning T[K], using key remapping with as. Then write validate<T>(values: T, validators: Validators<T>): Errors<T> (loop over Object.keys(validators) as (keyof T)[]) and makeGetters(values: Signup): Getters<Signup>. Validate two signups and print the errors, then call getAge() on the getters.

TypeScript
type Signup = { email: string; age: number; terms: boolean };

// 1. Validators<T>

// 2. Errors<T>

// 3. Getters<T>

// validate() and makeGetters()

Summary

  • A mapped type loops over keys: { [K in keyof T]: … } creates one property per key of T.
  • Use T[K] inside to refer to each property’s original type, and transform it as needed.
  • Add or remove modifiers with readonly, -readonly, ? and -? — that’s how Partial, Required and Readonly work.
  • as renames keys (often with template literal types) and can filter them out by mapping to never.
  • Mapped types keep related types in sync with a source type: forms, validators, getters, event handlers.