TypeScript by Example

Key Remapping

Renaming and filtering keys inside mapped types with as, template literals, and never.

Key remapping uses as inside a mapped type to rename or remove keys while building a new object type.

Combine as with template literal types to derive method names from field names.

type Model = {
  id: string;
  name: string;
  createdAt: Date;
};
 
type Getters<T> = {
  [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K];
};
 
type ModelGetters = Getters<Model>;
// getId, getName, getCreatedAt

Map unwanted keys to never to filter them out.

type DataOnly<T> = {
  [K in keyof T as T[K] extends Function ? never : K]: T[K];
};
 
type ViewModel = DataOnly<{
  id: string;
  save(): void;
  updatedAt: Date;
}>;
// { id: string; updatedAt: Date }

In production

Key remapping is the idiomatic way to derive API view models, event handler names, and serializable snapshots from source types without maintaining a second hand-written shape.

Enjoyed this? Get more software craft delivered to your inbox.