Mapped types
7.0.2
Build a new object type from the fields of an existing type. Use this for related shapes that should stay in sync.
On this page
Visit each key in a type
keyof T gives the property names of T. The mapped type visits each key. T[Key] gives that property’s value type. Here every field becomes optional for a product update.
type Product = { name: string; quantity: number };
type Patch<T> = {
[Key in keyof T]?: T[Key];
};
const update: Patch<Product> = { quantity: 8 };
Change keys and modifiers
Use the as clause to rename keys. Use -? to remove optional and -readonly to make a field writable. These changes affect the type checked by the compiler.
type Getters<T> = {
[Key in Extract<keyof T, string> as `get${Capitalize<Key>}`]: () => T[Key];
};
type ProductGetters = Getters<Product>;
// { getName: () => string; getQuantity: () => number }