Mapped Type Key Remapping
February 9, 20261 min readpart 07/20
Difficulty: Intermediate. Prerequisites: Mapped types, template literal types, keyof operator.
Key remapping in mapped types (TS 4.1+) allows you to transform the keys of an object type during mapping using the 'as' clause. This enables powerful transformations like prefixing/suffixing keys, filtering keys, and creating entirely new object shapes from existing types.
Key concepts
- Using 'as' clause in mapped types for key transformation
- Combining with template literal types for string manipulation
- Filtering keys by returning 'never' to exclude them
- Creating getters/setters, prefixed methods, and event handlers
Example
// Getters
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };
interface Person { name: string; age: number; }
type PG = Getters<Person>; // { getName: () => string; getAge: () => number }
// Filter keys
type OnlyStrings<T> = { [K in keyof T as T[K] extends string ? K : never]: T[K] };
// Remove specific key
type RemoveKind<T> = { [K in keyof T as Exclude<K, 'kind'>]: T[K] };
// Event handlers
type Events<E extends string> = { [K in E as `on${Capitalize<K>}`]: () => void };
type E = Events<'click' | 'hover'>; // { onClick: () => void; onHover: () => void }
// Getters + Setters
type Accessors<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
} & {
[K in keyof T as `set${Capitalize<string & K>}`]: (v: T[K]) => void
};
// Real-world: type-fest — CamelCasedProperties<T> = { [K in keyof T as CamelCase<K>]: T[K] }Resources
- TypeScript 4.1 - Key Remapping: Feature introduction
- TypeScript Handbook - Mapped Types: Comprehensive documentation
Practice
- Mapped Types (TypeHero, Medium)
- Pick (TypeHero, Easy)
- Omit (TypeHero, Medium)
- Readonly 2 (TypeHero, Medium)
- Omit (Type Challenges, Medium)
- Readonly 2 (Type Challenges, Medium)
- Deep Readonly (Type Challenges, Medium)
- Remove Index Signature (Type Challenges, Medium)
Hints
- Use "as never" to filter out keys you don't want in the resulting type.
- Combine key remapping with Capitalize to create getter/setter patterns.