Sub topic 14
Mapped Types with `keyof`
This chapter assumes you know basic TypeScript types, interfaces, and generic type parameters. It also assumes you can read an object type such as { title: string; done: boolean }.
A mapped type creates a new type by iterating over the property keys of another type. The keyof operator produces a union of those keys.
interface Todo {
title: string;
done: boolean;
note: string;
}
type TodoKey = keyof Todo;
// "title" | "done" | "note"The TodoKey type is a union of string literal types. A mapped type can use that union to create one property for each key.
Creating a mapped type
The basic syntax is:
type NewType<T> = {
[K in keyof T]: SomeType;
};K represents one key at a time. The expression keyof T supplies the keys. The value type after the colon applies to every resulting property.
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;
// }
const flags: TodoFlags = {
title: true,
done: false,
note: true,
};The mapped type preserves the property names but replaces their value types with boolean.
Making reusable transformations
Mapped types become useful when one transformation applies to many related shapes. TypeScript includes several common mapped types:
| Utility type | Effect |
|---|---|
| `Partial<T>` | Makes every property optional |
| `Readonly<T>` | Makes every property readonly |
| `Pick<T, K>` | Keeps only selected keys |
| `Omit<T, K>` | Removes selected keys |
For example, Partial<Todo> is similar to this mapped type:
type MyPartial<T> = {
[K in keyof T]?: T[K];
};
interface Todo {
title: string;
done: boolean;
note: string;
}
type TodoDraft = MyPartial<Todo>;
const draft: TodoDraft = {
title: "Read chapter",
};T[K] means “the value type at key K.” This preserves the original value types while adding ? to each property.
You can also remove or add modifiers. A minus sign removes a modifier:
type RequiredTodo<T> = {
[K in keyof T]-?: T[K];
};
type MutableTodo<T> = {
-readonly [K in keyof T]: T[K];
};RequiredTodo<T> makes every property required. MutableTodo<T> removes readonly.
Common errors
A mapped type must iterate over a valid property-key union. Using keyof T is the usual choice. Also remember that a type transformation does not change an existing value at runtime. It only changes what the compiler allows.
Mapped types are often clearer than repeating similar object shapes. Keep the transformation small and give it a name that explains its purpose.
Exercise
Define a generic Nullable<T> mapped type that keeps every property of T but allows each property to also be null.
Show answer
type Nullable<T> = { [K in keyof T]: T[K] | null };