Key remapping with the as clause lets you change the names of keys when creating a new object type from an existing one. This helps make your code clearer and easier to use.
0
0
Key remapping with as clause in Typescript
Introduction
When you want to rename keys in an object type to better match your app's naming style.
When you need to create a new type with keys that are easier to understand or shorter.
When integrating with APIs that use different key names than your codebase.
When you want to avoid key name conflicts by renaming keys in a new type.
Syntax
Typescript
type NewType = {
[OldKey in keyof OldType as NewKey]: OldType[OldKey]
}The as clause lets you rename each key from OldKey to NewKey.
You can use conditional logic inside as to rename keys selectively.
Examples
This example adds
person_ before each key name.Typescript
type Person = {
firstName: string;
lastName: string;
};
type RenamedPerson = {
[K in keyof Person as `person_${K}`]: Person[K]
};This example renames key
a to alpha, and keeps others the same.Typescript
type Original = {
a: number;
b: string;
c: boolean;
};
type Remap = {
[K in keyof Original as K extends 'a' ? 'alpha' : K]: Original[K]
};Sample Program
This program renames the username key to user_name in the new type. Then it creates an object with the new keys and prints it.
Typescript
type User = {
id: number;
username: string;
email: string;
};
type UserWithRenamedKeys = {
[Key in keyof User as Key extends 'username' ? 'user_name' : Key]: User[Key]
};
const user: UserWithRenamedKeys = {
id: 1,
user_name: 'alice',
email: 'alice@example.com'
};
console.log(user);OutputSuccess
Important Notes
Key remapping only changes the key names in the type, not the actual values.
You can use template literal types inside as for flexible renaming.
This feature helps keep your types clean and consistent with your code style.
Summary
Use as in mapped types to rename keys.
It helps adapt existing types to new naming conventions.
Works well with conditional and template literal types for flexible renaming.