patterntypescriptnoneTip
Mapped Types to Transform Object Shapes
Viewed 0 times
TypeScript 2.1+ (key remapping 4.1+)
mapped typekeyofkey remappingutility typeobject transformation
Problem
You need to derive a new type from an existing one (make all fields optional, readonly, or transform value types) without manually duplicating the interface.
Solution
Use mapped types with 'keyof' to iterate over a type's keys and transform them.
// Make all properties nullable
type Nullable<T> = { [K in keyof T]: T[K] | null };
// Make all properties async getters
type AsyncGetters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => Promise<T[K]>;
};
interface User { name: string; age: number; }
type AsyncUser = AsyncGetters<User>;
// { getName: () => Promise<string>; getAge: () => Promise<number>; }
// Filter keys by value type
type PickByValue<T, V> = {
[K in keyof T as T[K] extends V ? K : never]: T[K];
};
type StringFields = PickByValue<User, string>; // { name: string }Why
Mapped types iterate over a union of keys (usually 'keyof T') and produce a new object type. Key remapping with 'as' enables filtering and renaming keys.
Gotchas
- Key remapping ('as' clause) requires TypeScript 4.1+.
- Mapped types always produce object types; they cannot create tuple types.
- Homomorphic mapped types (using keyof T) preserve optional/readonly modifiers; non-homomorphic ones do not.
Revisions (0)
No revisions yet.