TypeScript Mapped Types
Often you need a type that is "the same as that other type, but slightly different": every property optional, every property read-only, every value turned into a function, and so on. Writing those by hand means repeating yourself and keeping two types in sync forever. A mapped type generates a new object type by looping over the keys of an existing one.
The basic form
A mapped type looks like an index signature with in:
type NewType = { [K in SomeKeys]: SomeValueType };K takes each member of the union SomeKeys in turn, and one property is produced for each. Most of the time the keys come from keyof another type:
interface User {
id: number;
username: string;
active: boolean;
}
type Flags<T> = { [K in keyof T]: boolean };
type Stringified<T> = { [K in keyof T]: string };
const changed: Flags<User> = { id: false, username: true, active: false };
const form: Stringified<User> = { id: "7", username: "minh", active: "yes" };
console.log(changed);
console.log(form);{ id: false, username: true, active: false }
{ id: '7', username: 'minh', active: 'yes' }
Inside the mapping, T[K] refers to the original type of the property, so you can transform values rather than replace them:
interface Settings {
volume: number;
muted: boolean;
}
type Getters<T> = { [K in keyof T]: () => T[K] };
const settings: Settings = { volume: 7, muted: false };
const getters: Getters<Settings> = {
volume: () => settings.volume,
muted: () => settings.muted,
};
console.log(getters.volume() + 1, getters.muted());8 false
Modifiers: ? and readonly
You can add or remove the optional (?) and readonly modifiers. A - in front removes a modifier, a + (or nothing) adds it:
| Mapping | Effect | Built-in equivalent |
|---|---|---|
{ [K in keyof T]?: T[K] } |
all optional | Partial<T> |
{ [K in keyof T]-?: T[K] } |
all required | Required<T> |
{ readonly [K in keyof T]: T[K] } |
all read-only | Readonly<T> |
{ -readonly [K in keyof T]: T[K] } |
remove read-only | (none — write it yourself) |
{ [K in Keys]: V } |
fixed keys, one value type | Record<Keys, V> |
Yes — the utility types you met earlier (Partial, Readonly, Record, Pick) are just mapped types in the standard library. Here's a homemade Mutable and a Partial in action:
type Mutable<T> = { -readonly [K in keyof T]: T[K] };
type MyPartial<T> = { [K in keyof T]?: T[K] };
interface Config {
readonly host: string;
readonly port: number;
}
const frozen: Config = { host: "localhost", port: 8080 };
const editable: Mutable<Config> = { ...frozen };
editable.port = 3000;
const patch: MyPartial<Config> = { port: 9000 };
const merged: Config = { ...frozen, ...patch };
console.log(editable.port, merged);
frozen.port = 1;main.ts(17,8): error TS2540: Cannot assign to 'port' because it is a read-only property.
The last line is the expected error: frozen still has the read-only type, only the mapped copy is mutable. Delete it to see the program run.
Key remapping with as
Since TypeScript 4.1 you can rename keys while mapping, by adding as NewKey after the in clause. Combined with template literal types, this creates new property names from old ones:
interface Product {
title: string;
price: number;
}
type Setters<T> = {
[K in keyof T as `set${Capitalize<string & K>}`]: (value: T[K]) => void;
};
const item: Product = { title: "Lamp", price: 30 };
const setters: Setters<Product> = {
setTitle: (v) => { item.title = v; },
setPrice: (v) => { item.price = v; },
};
setters.setPrice(25);
setters.setTitle("Desk lamp");
console.log(item);{ title: 'Desk lamp', price: 25 }
(string & K keeps only string keys, since Capitalize can't work on number or symbol keys.)
Filtering keys
If the as clause produces never, that key is dropped. This lets you keep only properties of a certain type:
type PickByValue<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K];
};
interface Order {
id: number;
customer: string;
total: number;
note: string;
paid: boolean;
}
type NumericFields = PickByValue<Order, number>; // { id: number; total: number }
const nums: NumericFields = { id: 12, total: 99.5 };
console.log(Object.keys(nums));[ 'id', 'total' ]
The T[K] extends V ? K : never part is a conditional type, which the next lesson covers in depth.
Tip: Hover over a mapped type in your editor to see the resulting properties. If the hover shows the unexpanded form, wrapping it as
type Show<T> = { [K in keyof T]: T[K] } & {}often makes the editor print it out.
Test yourself
What does { [K in keyof T]?: T[K] } produce?
- A type with all properties required
- A type with all properties optional
- A type with only the keys
- An array of T
How do you remove the readonly modifier in a mapped type?
!readonly-readonlyreadonly?delete readonly
In a key remapping as clause, what happens to a key mapped to never?
- It becomes optional
- It is renamed to "never"
- It is removed from the result
- Compilation fails