Basic Key Transformation Patterns
You'll learn how to use mapped types with key remapping to transform property names by adding prefixes, suffixes, or changing their case.
When you introduced key remapping with as in the previous lesson, you unlocked the ability to rename properties as you map over them. Now let's explore the most common transformation patterns you'll encounter in real-world TypeScript.
Simple Transformations
The key remapping clause as lets you take each property key (represented as a string literal type) and transform it. Here are the fundamental patterns:
Adding Prefixes:
type Prefixed<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: T[K]
}
type User = { name: string; age: number }
type WithGetters = Prefixed<User>
// { getName: string; getAge: number }
Adding Suffixes:
type Suffixed<T> = {
[K in keyof T as `${string & K}Changed`]: T[K]
}
type Events = Suffixed<User>
// { nameChanged: string; ageChanged: number }
Case Transformation:
type Uppercase<T> = {
[K in keyof T as Uppercase<string & K>]: T[K]
}
type Constants = UpperKeys<User>
// { NAME: string; AGE: number }
Why string & K?
The string & K intersection ensures that K is treated as a string type for template literal manipulation, filtering out symbol or number keys that can't be transformed this way.
Real-World Use
These patterns appear in frameworks that generate API methods from models, create event handler names from properties, or transform configuration objects to match different naming conventions.
Key Takeaway: Key remapping with as enables systematic property name transformations using template literals and string utility types like Capitalize, Uppercase, and Lowercase.