Sub topic 9
Building Mapped Types with `keyof`
Assume you know TypeScript interfaces, type aliases, union types, and basic generics. You should also be comfortable reading T[K], where K is a property key. Mapped types build a new object type by iterating over the keys of an existing type.
The basic mapped type
A mapped type uses this pattern:
type NewType<T> = {
[K in keyof T]: /* type for property K */;
};Here:
keyof Tproduces a union of the keys inT.Krepresents one key at a time.T[K]looks up the type of the property represented byK.- The mapped type creates a new property for every key.
For example, this type makes every property nullable:
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;
// }When TypeScript evaluates Nullable<Point>, keyof Point becomes "x" | "y". The mapped type visits both keys and adds null to each property's original type.
Changing property modifiers
Mapped types can change whether properties are optional or readonly. A question mark controls optionality, and readonly controls reassignment.
Use ? to make every property optional:
type Optional<T> = {
[K in keyof T]?: T[K];
};
interface User {
id: number;
name: string;
}
type OptionalUser = Optional<User>;
// {
// id?: number;
// name?: string;
// }Use -? to remove optionality. Use +? to add it explicitly. The plus sign is usually optional because addition is the default.
interface Profile {
name?: string;
age?: number;
}
type RequiredProfile = {
[K in keyof Profile]-?: Profile[K];
};
// {
// name: string;
// age: number;
// }The same syntax works with readonly:
type ReadonlyCopy<T> = {
readonly [K in keyof T]: T[K];
};
type MutableCopy<T> = {
-readonly [K in keyof T]: T[K];
};ReadonlyCopy<User> prevents assignment to its properties. MutableCopy removes an existing readonly modifier.
Combining keys and indexed access
Mapped types often use T[K] because each property can receive a type based on its original value.
This example creates a validation result for every property:
type Validation<T> = {
[K in keyof T]: {
value: T[K];
valid: boolean;
};
};
interface Settings {
theme: string;
notifications: boolean;
}
type SettingsValidation = Validation<Settings>;
// {
// theme: { value: string; valid: boolean };
// notifications: { value: boolean; valid: boolean };
// }
const result: SettingsValidation = {
theme: { value: "dark", valid: true },
notifications: { value: true, valid: true },
};
console.log(result.theme.value);The expression T[K] keeps the relationship between each key and its value type. The theme value must be a string, while the notifications value must be a boolean.
A mapped type as a transformation
Think of a mapped type as a type-level loop:
flowchart TD
A["Point: x is number, y is number"] --> B["keyof Point: x | y"]
B --> C["Visit each key K"]
C --> D["Read T[K]"]
D --> E["Build the transformed property"]
E --> F["NullablePoint: x and y allow null"]This loop exists only during type checking. It does not create a runtime loop or JavaScript object.
Common errors
A mapped type must iterate over a valid property-key union. The usual source is keyof T, but a fixed union also works:
type Flags = {
[K in "darkMode" | "compactMode"]: boolean;
};
const flags: Flags = {
darkMode: true,
compactMode: false,
};Do not confuse a mapped type with an index signature:
type AnyBooleanMap = {
[key: string]: boolean;
};This index signature allows any string key. A mapped type over "darkMode" | "compactMode" allows exactly those known keys.
Mapped types also do not validate runtime data. If data comes from JSON or user input, you still need runtime validation before trusting its shape.
Exercise
What type does Nullable<{ count: number; label: string }> produce?
Show answer
It produces { count: number | null; label: string | null }.