Sub topic 9
Building mapped types with keyof
This chapter assumes you know interfaces, type aliases, union types, and basic generics. It also assumes you have met keyof T (the union of an object type's keys) and T[K] (the type of one property) from earlier chapters. A mapped type combines those two pieces to build a new object type from an existing one.
What a mapped type is
A mapped type creates an object type by looping over a union of keys. For each key it produces one property. The most common loop is over keyof T, which means "one new property for every property of T".
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
interface Point {
x: number;
y: number;
}
type NullablePoint = Nullable<Point>; // { x: number | null; y: number | null }
const p: NullablePoint = { x: 1, y: null };
console.log(p);The syntax [K in keyof T] has three parts:
| Part | Meaning | Column |
|---|---|---|
| `K` | A type variable that takes each key in turn, one at a time. | |
| `in` | Iterates over the union that follows. | |
| `keyof T` | The union of keys to iterate over. For `Point` it is `"x" \ | "y"`. |
| `T[K]` | An indexed access type. It gives the original type of the property `K`. |
The result is built as if you had written out each property by hand. For Point, TypeScript evaluates the mapping twice: once with K = "x" and once with K = "y".
Why the key stays linked to the value
You could write [K in keyof T]: string and ignore K in the value. That is legal, but the useful mapped types read T[K]. This keeps each new property tied to the matching original property. If someone adds a field to Point, Nullable<Point> gains that field with no edit.
You can also transform the value type with a conditional type:
type Stringify<T> = {
[K in keyof T]: T[K] extends number ? string : T[K];
};
interface Row {
id: number;
label: string;
}
type DisplayRow = Stringify<Row>; // { id: string; label: string }
const row: DisplayRow = { id: "42", label: "Answer" };
console.log(row);Modifiers: readonly and optional
A mapped type can add or remove the readonly and ? modifiers. Write + or nothing to add a modifier. Write - to remove it.
interface User {
readonly id: number;
name: string;
email?: string;
}
type MyPartial<T> = { [K in keyof T]?: T[K] };
type MyRequired<T> = { [K in keyof T]-?: T[K] };
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type PartialUser = MyPartial<User>; // { readonly id?: number; name?: string; email?: string }
type RequiredUser = MyRequired<User>; // { readonly id: number; name: string; email: string }
type MutableUser = Mutable<User>; // { id: number; name: string; email?: string }
const u: MutableUser = { id: 1, name: "Ada" };
u.id = 2; // allowed, because readonly was removed
console.log(u);These three types match the built-in Partial, Required, and the common community Mutable helper. Readonly<T> is the same pattern with readonly added.
Notice what -? did to email. Its type was string | undefined, and Required gives string. With -?, TypeScript also strips the undefined that optionality added.
Homomorphic mapped types keep modifiers
When the key union is exactly keyof T for some type T, the mapped type is called homomorphic. It copies the readonly and ? modifiers from T automatically. That is why Nullable<User> keeps id readonly and email optional without you saying so.
The same rule applies when the key type is a parameter constrained to keyof T:
type MyPick<T, K extends keyof T> = {
[P in K]: T[P];
};
type NameOnly = MyPick<{ readonly id: number; name: string }, "name">; // { name: string }
type IdOnly = MyPick<{ readonly id: number; name: string }, "id">; // { readonly id: number }If you loop over a plain union that has no link to a source type, nothing is copied. The properties are created fresh, with no readonly and no ?.
Looping over any union of keys
keyof T is only one source of keys. K in accepts any union of string, number, or symbol types. This is how a list of literals becomes an object type. The ROLES array below uses the as const and T[number] pattern from earlier chapters.
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = (typeof ROLES)[number]; // "admin" | "editor" | "viewer"
type Permissions = { [R in Role]: boolean };
const permissions: Permissions = {
admin: true,
editor: true,
viewer: false,
};
// Omitting a role is now a compile-time error:
// const broken: Permissions = { admin: true, editor: true }; // Error: 'viewer' is missing
console.log(permissions);This shape is common enough that the built-in Record<K, V> provides it. Record<Role, boolean> is equivalent to Permissions. Use a mapped type instead of Record when the value type depends on the key, as T[K] does.
Remapping keys with as
Since TypeScript 4.1 you can rename keys inside the loop with an as clause. The clause computes a new key for each K.
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
interface Person {
name: string;
age: number;
}
type PersonGetters = Getters<Person>;
// { getName: () => string; getAge: () => number }
const getters: PersonGetters = {
getName: () => "Ada",
getAge: () => 36,
};
console.log(getters.getName(), getters.getAge());The expression string & K is needed because keyof T can include number and symbol keys, and Capitalize only accepts strings. Intersecting with string keeps only the string keys.
Filtering properties by mapping a key to never
If the as clause produces never, that property is dropped. This lets you filter an object type by the type of its values:
type OnlyStrings<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
interface Item {
id: number;
name: string;
email: string;
active: boolean;
}
type StringProps = OnlyStrings<Item>; // { name: string; email: string }
const s: StringProps = { name: "Ada", email: "[email protected]" };
console.log(s);Remapping with as still reads T[K] using the original key. The K on the right side of the colon is the old key, not the renamed one. Remapping also keeps the modifiers of the source properties, because the loop is still over keyof T.
How mapped types treat arrays and tuples
When a homomorphic mapped type is applied to an array or tuple type, TypeScript maps the elements instead of the property names. You get an array or tuple back, not an object with keys like "length".
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]
const a: A = [1, null, 3];
const b: B = ["x", null];
console.log(a, b);This only happens when T is a type parameter that is later given an array or tuple type, as in the Nullable<T> helper here. A hand-written { [K in keyof string[]]: ... } does not get this treatment.
Edge cases and common errors
The following rules cause most surprises with mapped types.
- Index signatures are preserved.
keyof { [key: string]: boolean }isstring | number, soNullableof that type is{ [x: string]: boolean | null }. You do not get a fixed list of properties. - Unions are distributed in a specific way. A homomorphic mapped type applied to a union maps each member separately.
Nullable<A | B>isNullable<A> | Nullable<B>. It is not one object with only the shared keys. - Key type must be assignable to
string | number | symbol. Writing[K in boolean]is an error. Writing[K in string]is allowed and produces an index signature. - Optional properties add
undefined.T[K]for an optional property includesundefined. If you map with-?theundefinedis removed, but if you only copyT[K]into a non-optional position you keep it. - Mapped types describe types, not runtime code. A mapped type can change what the compiler believes about an object. It cannot create the properties. The assignment
const x = {} as Permissionscompiles, butx.adminisundefinedat runtime.
Putting it together
The next example combines key remapping, a lookup with T[K], and a typed runtime function. It builds an event-handler type from a map of event payloads:
interface Events {
login: { user: string };
logout: { user: string; reason: string };
}
type Handlers<T> = {
[K in keyof T as `on${Capitalize<string & K>}`]: (payload: T[K]) => void;
};
type EventHandlers = Handlers<Events>;
// {
// onLogin: (payload: { user: string }) => void;
// onLogout: (payload: { user: string; reason: string }) => void;
// }
const handlers: EventHandlers = {
onLogin: (payload) => console.log(`${payload.user} signed in`),
onLogout: (payload) => console.log(`${payload.user} left: ${payload.reason}`),
};
handlers.onLogin({ user: "ada" });
handlers.onLogout({ user: "ada", reason: "timeout" });The parameter payload in each handler gets a precise type without any annotation. The compiler infers it from T[K] for the matching key. If you add an event to Events, the compiler requires a matching handler, and in EventHandlers a missing handler is an error.
Exercises
Exercise
Write a mapped type Flags<T> that turns every property of T into a boolean, keeping the original keys. What is Flags<{ id: number; name: string }>?
Show answer
type Flags<T> = { [K in keyof T]: boolean }; The result is { id: boolean; name: boolean }. The value does not use T[K], so each property type is replaced by boolean. Because the loop is over keyof T, any readonly or optional modifiers on the source properties are kept.
Exercise
Write OmitByType<T, V> that removes every property of T whose value type is assignable to V. Use it to remove the number properties from { id: number; name: string; age: number }.
Show answer
type OmitByType<T, V> = { [K in keyof T as T[K] extends V ? never : K]: T[K] }; Then OmitByType<{ id: number; name: string; age: number }, number> is { name: string }. The as clause maps the key of every matching property to never, which drops it, and the other keys are kept unchanged.
Exercise
Given const LEVELS = ["low", "mid", "high"] as const;, define a type LevelCounts that has one number property for each level. What happens if you build a value of that type and leave out "mid"?
Show answer
type Level = (typeof LEVELS)[number]; type LevelCounts = { [L in Level]: number }; This gives { low: number; mid: number; high: number }. A value that omits "mid" is a compile-time error, because the property "mid" is required. The same type could be written as Record<Level, number>.