Sub topic 9
Mapped Types
Mapped types create a new type by iterating over the properties of another type. They are useful when several properties need the same transformation, such as making every property optional or read-only.
This chapter assumes you know basic TypeScript object types, interfaces, type aliases, keyof, indexed access types, and union types.
The Basic Pattern
A mapped type uses a property key in brackets:
type Mapped<T> = {
[K in keyof T]: T[K];
};Read this as: “For each key K in T, create a property named K with the original property type T[K].”
The result has the same shape as T:
interface User {
id: number;
name: string;
}
type Copy<T> = {
[K in keyof T]: T[K];
};
type UserCopy = Copy<User>;
// {
// id: number;
// name: string;
// }keyof User produces the union "id" | "name". The mapped type visits each member of that union.
Changing Property Modifiers
Mapped types can add or remove property modifiers. A question mark controls optionality, and readonly controls assignment.
interface Settings {
theme: string;
fontSize: number;
}
type OptionalSettings<T> = {
[K in keyof T]?: T[K];
};
type ReadonlySettings<T> = {
readonly [K in keyof T]: T[K];
};
const draft: OptionalSettings<Settings> = {
theme: "dark"
};
const fixed: ReadonlySettings<Settings> = {
theme: "light",
fontSize: 16
};
// fixed.theme = "dark"; // Error: cannot assign to a read-only propertyUse -? to remove optionality and -readonly to remove read-only status:
type RequiredSettings<T> = {
[K in keyof T]-?: T[K];
};
type MutableSettings<T> = {
-readonly [K in keyof T]: T[K];
};The built-in Partial<T> and Readonly<T> utility types use this same idea.
Selecting and Transforming Keys
You can map only a subset of keys by using a key union:
interface Todo {
title: string;
done: boolean;
notes: string;
}
type TodoFlags = {
[K in "done"]: Todo[K];
};
const flags: TodoFlags = {
done: false
};A more reusable version accepts the selected keys as a type parameter:
type Select<T, K extends keyof T> = {
[P in K]: T[P];
};
type TodoSummary = Select<Todo, "title" | "done">;
const summary: TodoSummary = {
title: "Learn mapped types",
done: false
};The constraint K extends keyof T prevents callers from selecting a property that does not exist.
Common Errors
| Problem | Why it happens | Better approach |
|---|---|---|
| Using `T[K]` without constraining `K` | `K` might not be a key of `T` | Write `K extends keyof T` |
| Forgetting `?` | Properties remain required | Add `?` when creating a partial type |
| Treating a mapped type as runtime code | Mapped types disappear after compilation | Use JavaScript logic when values must change |
| Mapping every key unnecessarily | The resulting type becomes hard to understand | Map only the properties the API needs |
Practice
Exercise
Write a generic type named Mutable that removes readonly from every property of T.
Show answer
type Mutable<T> = { -readonly [K in keyof T]: T[K]; };