Sub topic 14
Mapped types with keyof
This chapter assumes you can write interfaces and type aliases, and that you have seen generics and the built-in utility types Partial, Pick, Omit, and Readonly. Here you will build the mechanism behind those utilities: the mapped type. By the end you should be able to write your own, read the ones in the standard library, and avoid the common mistakes.
The idea: a type that loops over keys
A mapped type creates a new object type by walking over a list of keys and deciding what each property looks like. The syntax is a type alias whose body is an object type with a computed key:
interface Todo {
title: string;
done: boolean;
note: string;
}
type Flags<T> = { [K in keyof T]: boolean };
type TodoFlags = Flags<Todo>; // { title: boolean; done: boolean; note: boolean }Two pieces do the work:
keyof Tis the type operator that produces a union of the property names ofT. ForTodo,keyof Todois"title" | "done" | "note".[K in ...]is the mapping clause. It visits each member of the union once, binds it toK, and creates a property namedK.
The value type after the colon can use K. That is how a mapped type can say "the same type as in the source" instead of a fixed boolean:
type Same<T> = { [K in keyof T]: T[K] };T[K] is an indexed access type. It looks up the type of property K in T. Same<Todo> is structurally identical to Todo.
Only type aliases can hold a mapped type. An interface cannot contain a [K in ...] clause. You can still use the result anywhere you would use an interface, including as the target of a class ... implements check, as long as the result is a plain object type with statically known keys.
Reading keyof
keyof deserves a closer look, because mapped types depend on it.
interface Point {
x: number;
y: number;
}
type PointKey = keyof Point; // "x" | "y"
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const p: Point = { x: 3, y: 4 };
const x: number = getProp(p, "x");
// getProp(p, "z"); // error: Argument of type '"z"' is not assignable to parameter of type '"x" | "y"'.The constraint K extends keyof T limits key to real property names, and the return type T[K] follows the chosen key. Mapped types use the same two tools in type-level form.
Some edge cases:
keyofon a type with a string index signature givesstring | number, because JavaScript converts numeric keys to strings. A number index signature givesnumber.keyofon a union of object types gives only the keys common to all members.keyofincludes optional properties. It does not include anything markedprivateorprotectedin a class.
Mapping over a union that is not keyof
The thing after in does not have to be keyof T. Any union of string, number, or symbol literals works. This is how Record is defined:
type Record2<K extends string | number | symbol, V> = { [P in K]: V };
type Status = "idle" | "loading" | "done";
type StatusLabels = Record2<Status, string>;
const labels: StatusLabels = {
idle: "Waiting",
loading: "Working",
done: "Finished",
};This is a useful pattern for exhaustiveness. If someone adds "failed" to Status, the labels object stops compiling until a label for "failed" is added. A plain { [key: string]: string } index signature would accept the missing entry silently.
Modifiers: readonly and optional
A mapped type can add or remove readonly and ? with + and - prefixes. A bare readonly or ? means +readonly or +?.
interface Config {
readonly host: string;
port?: number;
}
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type Required2<T> = { [K in keyof T]-?: T[K] };
type MutableConfig = Mutable<Config>; // { host: string; port?: number }
type FullConfig = Required2<Config>; // { readonly host: string; port: number }The built-in Readonly<T>, Partial<T>, and Required<T> are mapped types that add or remove these modifiers and nothing else.
| Utility | Mapped form |
|---|---|
| `Readonly<T>` | `{ readonly [K in keyof T]: T[K] }` |
| `Partial<T>` | `{ [K in keyof T]?: T[K] }` |
| `Required<T>` | `{ [K in keyof T]-?: T[K] }` |
| `Pick<T, K>` | `{ [P in K]: T[P] }` with `K extends keyof T` |
Homomorphic mapped types
When the mapping clause has the form [K in keyof T], TypeScript calls it homomorphic. A homomorphic mapped type copies the readonly and optional modifiers from each source property unless you change them explicitly. That is why Same<Config> above keeps readonly host and port?.
A mapping over some other union does not copy modifiers, because there is no source property to copy from. Record2<"a" | "b", number> produces plain required, writable properties.
Pick is a special case. Its key parameter is declared K extends keyof T, and TypeScript recognizes that the keys come from T, so Pick also preserves modifiers. Writing { [P in K]: T[P] } with K extends keyof T gives the same result.
Homomorphic mapped types also behave differently on primitives, arrays, and tuples. Mapping a generic T that is instantiated with string[] produces an array type, not an object with numeric keys:
type Nullable<T> = { [K in keyof T]: T[K] | null };
type A = Nullable<string[]>; // (string | null)[]
type B = Nullable<[number, string]>; // [number | null, string | null]This only works when T is a type parameter that is substituted with the array or tuple. If you write keyof against a concrete array type inside the mapped type, you get the array's methods as keys.
Remapping keys with as
Since TypeScript 4.1, a mapped type can rename keys with an as clause. Combined with template literal types, this builds getters, event names, and similar derived APIs.
interface Person {
name: string;
age: number;
}
type Getters<T> = {
[K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type PersonGetters = Getters<Person>;
// { getName: () => string; getAge: () => number }
const g: PersonGetters = {
getName: () => "Ada",
getAge: () => 36,
};The & string narrows keyof T to string keys, because Capitalize only accepts strings and keyof T may include number or symbol.
If the as clause evaluates to never, that key is dropped. This lets you filter properties by their type:
type OnlyStrings<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
interface Mixed {
id: number;
title: string;
author: string;
}
type TextFields = OnlyStrings<Mixed>; // { title: string; author: string }Omit can be written in this style, as { [K in keyof T as Exclude<K, Keys>]: T[K] }. The built-in Omit<T, K> is defined differently, as Pick<T, Exclude<keyof T, K>>, and its K is not constrained to keyof T. That means Omit<Todo, "typo"> compiles without complaint, which can hide a misspelled key.
A worked example: typed event handlers
This example combines keyof, a mapped type, and a generic function. It builds a handler map from an event description, so adding an event in one place forces handlers elsewhere.
interface Events {
open: { path: string };
close: { code: number };
}
type Handlers<E> = { [K in keyof E]: (payload: E[K]) => void };
const handlers: Handlers<Events> = {
open: (p) => console.log("opening", p.path),
close: (p) => console.log("closed with", p.code),
};
function emit<K extends keyof Events>(name: K, payload: Events[K]): void {
handlers[name](payload);
}
emit("open", { path: "/tmp/a.txt" });
// emit("close", { path: "/tmp/a.txt" }); // error: 'path' does not exist in type '{ code: number; }'The parameter p in each handler is inferred from the mapped type, so you do not annotate it. If you add save: { id: number } to Events, handlers fails to compile until a save handler exists.
One caution. Inside emit, the call handlers[name](payload) relies on TypeScript's handling of correlated unions for indexed access types. It compiles here because Handlers<Events>[K] resolves to a function taking Events[K]. If you restructure the types so the correlation is lost, you may see an error about an intersection of parameter types. The usual fix is to keep the generic mapped-type shape rather than widening it to a union.
Common errors
- Writing a mapped type inside an interface.
interface X { [K in keyof T]: ... }is a syntax error. Use a type alias. - Adding other members next to the mapping clause.
{ [K in keyof T]: string; extra: number }is an error. Intersect instead:{ [K in keyof T]: string } & { extra: number }. - Expecting a mapped type to merge like an interface. A type alias name can be declared only once.
- Forgetting
& stringbeforeCapitalizeor other string manipulation types onkeyof T. - Using
Omitwith a misspelled key. It accepts anystring | number | symbol. - Mapping over a union of object types and expecting each member to be handled separately. A homomorphic mapped type does distribute over a union when
Tis a naked type parameter, but a non-generic use does not. - Heavy recursive mapped types. Deep mapped types such as a
DeepPartialare fine for configuration objects, but they slow the compiler on very large types and can hit instantiation depth limits.
When to reach for a mapped type
Write a mapped type when a new shape is defined by a rule over an existing shape: every property becomes optional, every value becomes a function, every key gets a prefix. If you find yourself copying an interface and editing each line, a mapped type keeps the copy in sync automatically. If the new shape is a one-off with unrelated fields, a plain interface is easier to read.
Exercise
Given interface Product { id: number; name: string; price: number }, write a mapped type Validators<T> so that Validators<Product> is { id: (v: number) => boolean; name: (v: string) => boolean; price: (v: number) => boolean }. Then explain what happens to Validators<Product> if readonly is added to id in Product.
Show answer
type Validators<T> = { [K in keyof T]: (v: T[K]) => boolean }; Because the mapping is homomorphic (it uses keyof T), the readonly modifier on id is copied, so Validators<Product> also has a readonly id. To drop it, write -readonly [K in keyof T].
Exercise
Write a mapped type PickByType<T, V> that keeps only the properties of T whose value type is assignable to V. What does PickByType<Mixed, number> give for the Mixed interface in this chapter?
Show answer
type PickByType<T, V> = { [K in keyof T as T[K] extends V ? K : never]: T[K] }; For Mixed, the result is { id: number }, because title and author map to never in the as clause and are removed.