Sub topic 2
Mapped types: transforming every property
A mapped type builds a new object type by walking over a set of keys and deciding the property type for each one. It is the type-level version of a loop over an object's properties. This chapter covers the syntax, the most common shapes, and the errors you are likely to hit.
Prerequisites
This chapter assumes you can read object types, unions, and function types. It also assumes you know generics with extends constraints, and that you have seen keyof T and T[K] from the previous chapter. The two are summarized here:
keyof Tis the union of the property names ofT.T[K]is the type of the property namedKinT.
The basic shape
A mapped type has this form:
type Flags<T> = { [K in keyof T]: boolean };
type User = { id: number; name: string };
type UserFlags = Flags<User>;
// { id: boolean; name: boolean }Read [K in keyof T] as "for each member K of the union keyof T". Here keyof User is "id" | "name", so K takes the value "id" once and "name" once. The type after the colon is evaluated for each K and becomes that property's type.
The type after the colon can use K. Most useful mapped types read the original property type with T[K] and wrap or change it:
type Nullable<T> = { [K in keyof T]: T[K] | null };
type Promisified<T> = { [K in keyof T]: Promise<T[K]> };
type User = { id: number; name: string };
type NullableUser = Nullable<User>;
// { id: number | null; name: string | null }
type AsyncUser = Promisified<User>;
// { id: Promise<number>; name: Promise<string> }The mapping runs per property. id and name are handled independently, and the result has the same keys as the input.
The key set is just a union
The part after in does not have to be keyof T. It can be any type made of string, number, or symbol literals, or any union of them. keyof T is only the most common source of keys.
type Status = "idle" | "loading" | "done";
type StatusLabels = { [S in Status]: string };
// { idle: string; loading: string; done: string }
const labels: StatusLabels = {
idle: "Waiting",
loading: "Working",
done: "Finished",
};
console.log(labels.loading);If you add a new member to Status, every StatusLabels object that lacks the new key becomes a compile error. This is a common way to force a lookup table to stay complete.
This is also how the built-in Record works. You can rebuild it in one line:
type MyRecord<K extends PropertyKey, V> = { [P in K]: V };
type Scores = MyRecord<"alice" | "bob", number>;
// { alice: number; bob: number }PropertyKey is the built-in union string | number | symbol. The constraint K extends PropertyKey is required because only those types can be property names.
Choosing a subset of keys
When the key set is a subset of keyof T, you get Pick:
type MyPick<T, K extends keyof T> = { [P in K]: T[P] };
type User = { id: number; name: string; email: string };
type UserPreview = MyPick<User, "id" | "name">;
// { id: number; name: string }
// type Bad = MyPick<User, "age">;
// Error: Type '"age"' does not satisfy the constraint 'keyof User'.Two things matter here. The constraint K extends keyof T lets you use T[P] safely, because the compiler knows every P is a valid key of T. And the constraint rejects misspelled keys at the call site instead of silently producing a type with a missing property.
Rebuilding Partial
The topic's first example adds the optional marker ? to each property:
type User = { id: number; name: string };
type MyPartial<T> = { [K in keyof T]?: T[K] };
type PartialUser = MyPartial<User>;
// { id?: number; name?: string }The ? after the closing bracket applies to every generated property. The next chapter covers ? and readonly along with the + and - prefixes that add or remove them. For now, note that the modifier sits outside the brackets and the value type comes after the colon.
A mapped type in a real function
Mapped types matter most when a function's return type depends on its input type. This function applies a callback to every value of an object and returns an object with the same keys:
function mapValues<T extends object, R>(
obj: T,
fn: (value: T[keyof T]) => R
): { [K in keyof T]: R } {
const out = {} as { [K in keyof T]: R };
for (const key of Object.keys(obj) as Array<keyof T>) {
out[key] = fn(obj[key]);
}
return out;
}
const lengths = mapValues({ a: "x", b: "yyy" }, (v) => v.length);
// lengths: { a: number; b: number }
console.log(lengths.b); // 3The compiler infers T as { a: string; b: string } and R as number. The return type then expands to { a: number; b: number }, so lengths.b is a number and lengths.c is an error.
The as casts inside the function body are needed. Object.keys returns string[], and an empty object literal is not assignable to the mapped type. The signature is the part callers see and trust.
Common errors
Adding extra properties inside the braces
A mapped type may contain only the mapping. This does not compile:
// type WithId<T> = { [K in keyof T]: T[K]; id: number };
// Error: A mapped type may not declare properties or methods.Combine the mapped type with an intersection instead:
type WithId<T> = { [K in keyof T]: T[K] } & { id: number };
type Tagged = WithId<{ name: string }>;
// { name: string } & { id: number }Using a mapped type in an interface
A mapped type is only valid on the right side of a type alias. An interface cannot contain one directly. You can still extend an interface from a type alias if the alias resolves to an object type with statically known keys:
type Keys = "a" | "b";
type Mapped = { [K in Keys]: number };
interface Extended extends Mapped {
c: string;
}This works because Keys is a fixed union. It fails if the keys depend on an unresolved generic parameter.
Mapping over a key type that is not a property name
The key set must be made of types that can be property names. Mapping over boolean or an object type is an error. If your union holds objects, as in type Event = { kind: "a" } | { kind: "b" }, you cannot write [E in Event]. Map over the discriminant instead, as in [E in Event["kind"]].
Mapping over `string`
Using a wide key type produces an index signature, not a list of properties:
type Dict = { [K in string]: number };
// { [x: string]: number }
const d: Dict = { anything: 1, goes: 2 };
console.log(d.anything);This is useful when you want it. If you expected specific keys and got an index signature, the key set you passed was wider than a literal union.
What a mapped type does to arrays and tuples
When the mapping has the form [K in keyof T] and T is a type parameter, the compiler treats it as a mapping over the structure of T. If you pass an array or tuple type, you get an array or tuple back, not an object with numeric keys:
type Nullable<T> = { [K in keyof T]: T[K] | null };
type A = Nullable<number[]>;
// (number | null)[]
type B = Nullable<[string, number]>;
// [string | null, number | null]This behavior is called homomorphic mapping. A later chapter explains exactly when it applies. If you map over a plain union of literals instead of keyof T, no such preservation happens.
Checklist for writing a mapped type
- Decide the key set. Use
keyof Tto keep all keys, a constraint likeK extends keyof Tto select some, or a literal union you define. - Name the loop variable, usually
KorP. - Write the new property type. Use
T[K]if you need the original type. - Add
?orreadonlyoutside the brackets if you need to change modifiers. This is covered next. - Hover over a concrete use to confirm the expanded shape matches what you expect.
Exercise
Write a generic type Getters<T>-style helper called Lengths<T> that maps every property of T to number, and a type OnlyKeys<T, K> that keeps only the properties of T named in K but makes each one readonly-free string. Then explain why OnlyKeys<{ a: 1 }, "b"> should fail to compile, and what constraint produces that error.
Show answer
Lengths: type Lengths<T> = { [K in keyof T]: number };. OnlyKeys: type OnlyKeys<T, K extends keyof T> = { [P in K]: string };. The call OnlyKeys<{ a: 1 }, "b"> fails because "b" is not assignable to keyof { a: 1 }, which is "a". The constraint K extends keyof T produces the error "Type '"b"' does not satisfy the constraint '"a"'".
Exercise
Given type Status = "idle" | "loading" | "done", write a type StatusFlags that has one boolean property per status. What happens if you later add "error" to Status and you have a variable of type StatusFlags that has the three old keys?
Show answer
type StatusFlags = { [S in Status]: boolean };. After "error" is added, StatusFlags gains a required error: boolean property, so the existing variable fails to compile with an error that property error is missing. This is why mapped types over a union are a good way to keep tables complete.
Exercise
Why does type Bad<T> = { [K in keyof T]: T[K]; extra: string } fail, and how do you fix it?
Show answer
A mapped type may contain only the mapping and cannot declare other properties. Fix it with an intersection: type Good<T> = { [K in keyof T]: T[K] } & { extra: string }.