Sub topic 9
Mapped Types
This chapter assumes you can write generic functions and interfaces, and that you know keyof and indexed access types such as T[K]. A mapped type uses all of these to build a new object type from an existing one.
What a mapped type does
A mapped type walks over a set of keys and produces one property for each key. You can think of it as a for...in loop that runs on types.
type MyReadonly<T> = {
readonly [K in keyof T]: T[K];
};
interface Point {
x: number;
y: number;
}
const p: MyReadonly<Point> = { x: 1, y: 2 };
// p.x = 5; // Error: cannot assign to 'x' because it is a read-only propertyThe syntax has three parts:
Kis a type variable that takes each key in turn.keyof Tis the set of keys to visit. Any union of string, number, or symbol literal types works here.T[K]is the property type for the current key. It is an indexed access type, so it gives the original property's type.
The diagram shows how Point is transformed.
Changing the value type
The right-hand side can be any type expression, not just T[K].
type Nullable<T> = {
[K in keyof T]: T[K] | null;
};
interface Profile {
name: string;
age: number;
}
const draft: Nullable<Profile> = { name: "Ada", age: null };This pattern fits form state, API payloads where fields may be missing, and wrappers such as Promise or Ref. For example, { [K in keyof T]: Promise<T[K]> } describes an object whose fields are all asynchronous.
Modifiers: adding and removing readonly and optional
Mapped types can add or remove the readonly and ? modifiers. Write + or - in front of the modifier. A bare readonly or ? means +.
type Mutable<T> = {
-readonly [K in keyof T]: T[K];
};
type Concrete<T> = {
[K in keyof T]-?: T[K];
};
interface Settings {
readonly host: string;
port?: number;
}
type EditableSettings = Mutable<Settings>;
// { host: string; port?: number }
type FullSettings = Concrete<Settings>;
// { readonly host: string; port: number }
const s: EditableSettings = { host: "localhost" };
s.host = "example.com"; // allowedThe built-in Required<T> is -? and Partial<T> is +?. With strictNullChecks on, -? also removes undefined from the property type, which is why port becomes plain number.
Homomorphic mapped types
A mapped type is homomorphic when it iterates over keyof T for some type T. The same applies to K in keyof T where K ranges over keys taken from T, as in Pick. Two behaviors follow from this:
- The new type copies the
readonlyand?modifiers of the original properties. That is whyMyReadonly<Settings>keepsportoptional without any extra code. - When
Tis an array or tuple type, the result is an array or tuple, not an object with numeric keys.
type Stringify<T> = {
[K in keyof T]: string;
};
type Row = Stringify<[number, boolean]>; // [string, string]
type List = Stringify<number[]>; // string[]Copying modifiers happens only when the compiler can see keyof T in the mapped type. If you iterate over a plain union of keys, the properties start with no modifiers.
Mapping over a union of keys
You do not have to start from keyof T. Any union of literal keys works, and this is how Record is built.
type MyRecord<K extends PropertyKey, V> = {
[P in K]: V;
};
type Flags = MyRecord<"dark" | "compact", boolean>;
// { dark: boolean; compact: boolean }
const flags: Flags = { dark: true, compact: false };Using a literal union gives you exhaustiveness. If someone later adds "large" to the union, every object typed with Flags must be updated, and the compiler reports each place that is missing the key.
If you pass string as the key type, the result is an index signature, { [x: string]: V }. This is correct but much looser.
Remapping keys with `as`
An as clause after the iteration changes the name of each key. Inside it you can use template literal types and the string helpers Capitalize, Uncapitalize, Uppercase, and Lowercase.
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 g: PersonGetters = {
getName: () => "Ada",
getAge: () => 36,
};The string & K intersection is needed because keyof T can include number and symbol, and Capitalize accepts only strings. For a symbol key the intersection becomes never, and that key is dropped from the result.
Dropping a key is also how you filter. If the as clause evaluates to never, the property is omitted.
type OnlyStrings<T> = {
[K in keyof T as T[K] extends string ? K : never]: T[K];
};
interface Account {
id: number;
email: string;
displayName: string;
active: boolean;
}
type TextFields = OnlyStrings<Account>;
// { email: string; displayName: string }This uses a conditional type, which a later chapter covers in detail. Here it is enough to read X extends string ? A : B as "A if X is a string type, otherwise B".
The Omit utility type works the same way. A key-remapping version is { [K in keyof T as Exclude<K, "id">]: T[K] }.
Recursion: deep versions
Mapped types are shallow. Readonly<T> makes the top-level properties read-only, but nested objects stay mutable. To go deeper, make the mapped type refer to itself.
type DeepReadonly<T> = T extends (...args: never[]) => unknown
? T
: T extends object
? { readonly [K in keyof T]: DeepReadonly<T[K]> }
: T;
interface Config {
server: { host: string; ports: number[] };
}
declare const config: DeepReadonly<Config>;
// config.server.host = "x"; // Error: read-only
// config.server.ports[0] = 1; // Error: index signature only permits readingFunctions are checked first and returned unchanged. Without that branch, a function type would be mapped as an object and lose its call signature. Because the mapped type is homomorphic, number[] becomes readonly number[].
Gotchas
- Mapped types cannot declare extra members.
{ [K in "a" | "b"]: number; extra: string }is a syntax error. Combine with an intersection instead:{ [K in Keys]: number } & { extra: string }. - Readonly exists only at compile time.
Readonly<T>does not freeze the object at runtime. UseObject.freezeif you need that, and note that it is also shallow. - Modifier copying depends on the form.
{ [K in keyof T]: ... }preserves modifiers.{ [K in Keys]: ... }, whereKeysis a separately declared union, does not. If you extractkeyof Tinto a named alias and use that, you lose the modifiers. - Hover output can be hard to read. Nested mapped types often display as the mapped expression, not the final shape. Wrapping the result as
type Expand<T> = { [K in keyof T]: T[K] }forces the editor to show a flat object. Use this only for readability. - Heavy recursion is slow. Deep recursive mapped types can hit the compiler's instantiation depth limit or slow down editor feedback. Keep recursion shallow where you can.
The table below summarizes the common mapped-type shapes.
| Goal | Form | Example result |
|---|---|---|
| Transform every value | `{ [K in keyof T]: F<T[K]> }` | `Nullable<T>` |
| Add or remove modifiers | `{ -readonly [K in keyof T]-?: T[K] }` | `Mutable<T>`, `Concrete<T>` |
| Build from a key union | `{ [P in Keys]: V }` | `Record<Keys, V>` |
| Rename or filter keys | `{ [K in keyof T as NewKey]: T[K] }` | `Getters<T>`, `OnlyStrings<T>` |
Exercise
Write a type Setters<T> that maps { name: string; age: number } to { setName: (value: string) => void; setAge: (value: number) => void }. Which part of the mapped type syntax renames the keys, and why do you need string & K?
Show answer
Use key remapping with as:
type Setters<T> = {
[K in keyof T as set${Capitalize<string & K>}]: (value: T[K]) => void;
};
The as clause renames each key by wrapping it in a template literal type. string & K is needed because keyof T may include number and symbol keys, and Capitalize accepts only string types. Intersecting with string keeps just the string keys, and non-string keys become never, so they are dropped.
Exercise
Given interface User { readonly id: number; nickname?: string }, what are the types of Partial<User>, Required<User>, and { -readonly [K in keyof User]: User[K] }? Which modifiers do they keep from the original?
Show answer
Partial<User> is { readonly id?: number; nickname?: string }. It adds ? and keeps readonly on id. Required<User> is { readonly id: number; nickname: string }. It removes ? and keeps readonly. The third type is { id: number; nickname?: string }. It removes readonly and keeps the optional nickname. All three are homomorphic, so they copy the modifiers they do not explicitly change.