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.
Key remapping with as clause in 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.
person_ before each key name.type Person = {
firstName: string;
lastName: string;
};
type RenamedPerson = {
[K in keyof Person as `person_${K}`]: Person[K]
};a to alpha, and keeps others the same.type Original = {
a: number;
b: string;
c: boolean;
};
type Remap = {
[K in keyof Original as K extends 'a' ? 'alpha' : K]: Original[K]
};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.
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);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.
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.
Practice
What does the as clause do in a TypeScript mapped type?
Solution
Step 1: Understand mapped types
Mapped types create new types by transforming keys or values of an existing type.Step 2: Role of
Theasclauseasclause specifically allows renaming keys during this transformation.Final Answer:
It renames the keys of the original type to new keys. -> Option DQuick Check:
asclause = rename keys [OK]
as changes keys, not values [OK]- Thinking
aschanges values instead of keys - Confusing
aswith adding new keys - Assuming
asremoves keys
Which of the following is the correct syntax to rename keys in a mapped type using as?
type Original = { a: number; b: string };
type Renamed = { [K in keyof Original as ???]: Original[K] };Solution
Step 1: Understand template literal types in key remapping
To rename keys dynamically, template literals like`new_${K}`are used inside theasclause.Step 2: Check syntax correctness
Only`new_${K}`is valid syntax for renaming keys using template literals in TypeScript.Final Answer:
`new_${K}` -> Option BQuick Check:
Use template literals insideasfor renaming [OK]
- Using plus (+) operator instead of template literals
- Writing
as Kinside brackets incorrectly - Trying to cast keys with
as string
What is the resulting type of this code?
type User = { id: number; name: string };
type PrefixedUser = { [K in keyof User as `user_${K}`]: User[K] };Solution
Step 1: Analyze key remapping with template literals
The keysidandnameare renamed touserIdanduserNamerespectively using`user_${K}`.Step 2: Confirm values remain unchanged
The values for each key remain the same as inUser.Final Answer:
{ userId: number; userName: string } -> Option AQuick Check:
Keys renamed with prefix 'user_' [OK]
- Assuming keys stay the same
- Confusing camelCase with snake_case
- Expecting a syntax error
Identify the error in this mapped type:
type Data = { x: number; y: string };
type NewData = { [K in keyof Data as K.toUpperCase()]: Data[K] };Solution
Step 1: Check key remapping expression
The expressionK.toUpperCase()is a runtime string method and cannot be used in type-level key remapping.Step 2: Understand type-level string manipulation
TypeScript requires template literal types or conditional types for key transformations, not runtime methods.Final Answer:
Cannot usetoUpperCase()on type keys directly. -> Option AQuick Check:
Runtime methods disallowed in type keys [OK]
- Trying to call string methods on keys in types
- Confusing runtime and compile-time code
- Ignoring TypeScript's type system limits
Given this type, how would you create a new type that renames only keys starting with is by prefixing them with flag_, keeping others unchanged?
type Flags = { isActive: boolean; isAdmin: boolean; count: number };Solution
Step 1: Use conditional type in
The conditionasclauseK extends `is${string}`checks if the key starts with 'is'.Step 2: Rename keys conditionally
If true, rename key to`flag_${K}`, else keep original keyK.Step 3: Keep values unchanged
Values remain the same as inFlags.Final Answer:
type NewFlags = { [K in keyof Flags as K extends `is${string}` ? `flag_${K}` : K]: Flags[K] }; -> Option CQuick Check:
Conditional key renaming with template literals [OK]
as with template literals [OK]- Renaming all keys without condition
- Using runtime string methods in types
- Not preserving keys that don't match condition
Ready to prove it?
Pass the test and this pattern moves unknown
