Introducing Key Remapping with as
You'll learn how mapped types can transform property keys on the fly using the as clause.
When you create a mapped type, you're iterating over keys and transforming their values. But what if you need to rename the keys themselves? That's where the as clause comes in.
What Is Key Remapping?
Until now, our mapped types have preserved property names exactly as they appear in the source type. The as clause lets you remap each key to a different name during the mapping process.
Here's the basic syntax:
type Remapped<T> = {
[K in keyof T as NewKeyExpression]: T[K]
}
The as NewKeyExpression part transforms the key K into something else before creating the new property.
A Simple Example
Let's prefix all property names with get:
type User = {
name: string;
age: number;
};
type Getters<T> = {
[K in keyof T as `get${Capitalize<K & string>}`]: T[K]
};
type UserGetters = Getters<User>;
// { getName: string; getAge: number }
Here, each key K is remapped to a template literal that capitalizes and prefixes it.
Why This Matters
Key remapping unlocks patterns like:
- Creating getter/setter property names from data fields
- Converting snake_case to camelCase
- Filtering out properties by conditionally remapping to
never - Generating event handler names from event types
Key Takeaway: The as clause in mapped types allows you to transform property keys during mapping, not just their types—opening the door to powerful naming transformations and key-level filtering.