Bird
Raised Fist0
Typescriptprogramming~10 mins

Key remapping with as clause in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Key remapping with as clause
Start with object
↓
Destructure keys
↓
Use 'as' to rename keys
↓
Assign new variable names
↓
Use new variables in code
↓
End
This flow shows how to take keys from an object and rename them using 'as' during destructuring.
Execution Sample
Typescript
const user = { name: 'Alice', age: 30 };
const { name: userName, age: userAge } = user;
console.log(userName, userAge);
This code takes keys 'name' and 'age' from 'user' and renames them to 'userName' and 'userAge'.
Execution Table
StepActionExpressionResult
1Define objectconst user = { name: 'Alice', age: 30 }{ name: 'Alice', age: 30 }
2Destructure with renamingconst { name: userName, age: userAge } = useruserName = 'Alice', userAge = 30
3Log variablesconsole.log(userName, userAge)Output: Alice 30
4EndNo more codeExecution stops
💡 All keys destructured and renamed, program ends after logging.
Variable Tracker
VariableStartAfter Step 2Final
userundefined{ name: 'Alice', age: 30 }{ name: 'Alice', age: 30 }
userNameundefined'Alice''Alice'
userAgeundefined3030
Key Moments - 2 Insights
Why do we write 'name: userName' instead of just 'userName'?
Because 'name' is the original key in the object, and 'userName' is the new variable name we want to use. The 'as' clause syntax 'name: userName' means 'take the value of key name and store it in variable userName' (see execution_table step 2).
What happens if we write 'const { userName } = user;' without renaming?
It looks for a key named 'userName' in the object, which does not exist, so 'userName' will be undefined. The renaming with 'as' is necessary to map existing keys to new variable names.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table at step 2, what is the value of 'userAge'?
Aundefined
B30
C'age'
D'Alice'
💡 Hint
Check the 'Result' column in step 2 where 'userAge' is assigned.
At which step does the program output 'Alice 30'?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for the step where console.log is called in the execution_table.
If we change the code to 'const { age: userName } = user;', what will be the value of 'userName' after step 2?
A30
B'Alice'
Cundefined
DError
💡 Hint
Check how renaming works in the variable_tracker and execution_table step 2.
Concept Snapshot
Key remapping with 'as' clause:
const { originalKey: newVarName } = object;
- Extracts 'originalKey' from object
- Assigns its value to 'newVarName'
- Useful to rename variables during destructuring
- Keeps code clear and avoids naming conflicts
Full Transcript
This visual execution shows how to rename keys from an object during destructuring in TypeScript. We start with an object 'user' with keys 'name' and 'age'. Using the syntax 'const { name: userName, age: userAge } = user;', we extract the values of 'name' and 'age' and assign them to new variables 'userName' and 'userAge'. The execution table traces each step: defining the object, destructuring with renaming, logging the new variables, and ending the program. The variable tracker shows how 'userName' and 'userAge' get their values after destructuring. Key moments clarify why renaming is needed and what happens if we skip it. The quiz tests understanding of variable values at each step and effects of changing the renaming. This helps beginners see exactly how key remapping works in practice.

Practice

(1/5)
1.

What does the as clause do in a TypeScript mapped type?

easy
A. It adds new keys without changing existing ones.
B. It changes the values of the original type.
C. It removes keys from the original type.
D. It renames the keys of the original type to new keys.

Solution

  1. Step 1: Understand mapped types

    Mapped types create new types by transforming keys or values of an existing type.
  2. Step 2: Role of as clause

    The as clause specifically allows renaming keys during this transformation.
  3. Final Answer:

    It renames the keys of the original type to new keys. -> Option D
  4. Quick Check:

    as clause = rename keys [OK]
Hint: Remember: as changes keys, not values [OK]
Common Mistakes:
  • Thinking as changes values instead of keys
  • Confusing as with adding new keys
  • Assuming as removes keys
2.

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] };
easy
A. as K
B. `new_${K}`
C. K as string
D. K + 'Key'

Solution

  1. Step 1: Understand template literal types in key remapping

    To rename keys dynamically, template literals like `new_${K}` are used inside the as clause.
  2. Step 2: Check syntax correctness

    Only `new_${K}` is valid syntax for renaming keys using template literals in TypeScript.
  3. Final Answer:

    `new_${K}` -> Option B
  4. Quick Check:

    Use template literals inside as for renaming [OK]
Hint: Use backticks and ${} for key renaming [OK]
Common Mistakes:
  • Using plus (+) operator instead of template literals
  • Writing as K inside brackets incorrectly
  • Trying to cast keys with as string
3.

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] };
medium
A. { userId: number; userName: string }
B. { id: number; name: string }
C. { user_id: number; user_name: string }
D. Error: Invalid key remapping

Solution

  1. Step 1: Analyze key remapping with template literals

    The keys id and name are renamed to userId and userName respectively using `user_${K}`.
  2. Step 2: Confirm values remain unchanged

    The values for each key remain the same as in User.
  3. Final Answer:

    { userId: number; userName: string } -> Option A
  4. Quick Check:

    Keys renamed with prefix 'user_' [OK]
Hint: Template literals rename keys, values stay same [OK]
Common Mistakes:
  • Assuming keys stay the same
  • Confusing camelCase with snake_case
  • Expecting a syntax error
4.

Identify the error in this mapped type:

type Data = { x: number; y: string };
type NewData = { [K in keyof Data as K.toUpperCase()]: Data[K] };
medium
A. Cannot use toUpperCase() on type keys directly.
B. Missing return type for mapped type.
C. Keys must be numbers, not strings.
D. Values cannot be accessed with Data[K].

Solution

  1. Step 1: Check key remapping expression

    The expression K.toUpperCase() is a runtime string method and cannot be used in type-level key remapping.
  2. Step 2: Understand type-level string manipulation

    TypeScript requires template literal types or conditional types for key transformations, not runtime methods.
  3. Final Answer:

    Cannot use toUpperCase() on type keys directly. -> Option A
  4. Quick Check:

    Runtime methods disallowed in type keys [OK]
Hint: Use template literals, not runtime string methods [OK]
Common Mistakes:
  • Trying to call string methods on keys in types
  • Confusing runtime and compile-time code
  • Ignoring TypeScript's type system limits
5.

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 };
hard
A. type NewFlags = { [K in keyof Flags]: Flags[K] };
B. type NewFlags = { [K in keyof Flags as `flag_${K}`]: Flags[K] };
C. type NewFlags = { [K in keyof Flags as K extends `is${string}` ? `flag_${K}` : K]: Flags[K] };
D. type NewFlags = { [K in keyof Flags as K.toLowerCase()]: Flags[K] };

Solution

  1. Step 1: Use conditional type in as clause

    The condition K extends `is${string}` checks if the key starts with 'is'.
  2. Step 2: Rename keys conditionally

    If true, rename key to `flag_${K}`, else keep original key K.
  3. Step 3: Keep values unchanged

    Values remain the same as in Flags.
  4. Final Answer:

    type NewFlags = { [K in keyof Flags as K extends `is${string}` ? `flag_${K}` : K]: Flags[K] }; -> Option C
  5. Quick Check:

    Conditional key renaming with template literals [OK]
Hint: Use conditional as with template literals [OK]
Common Mistakes:
  • Renaming all keys without condition
  • Using runtime string methods in types
  • Not preserving keys that don't match condition
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard