0
0
Typescriptprogramming~5 mins

Key remapping with as clause in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the as clause do in TypeScript's key remapping?
It allows you to rename keys when creating new object types by mapping old keys to new keys.
Click to reveal answer
intermediate
How do you write a mapped type that changes keys from oldKey to newKey?
Use { [K in keyof T as NewKeyType]: T[K] } where NewKeyType is the new key name, often using as to rename.
Click to reveal answer
intermediate
Example: What is the result of this type?<br>
type Rename = { [K in keyof Original as `new_${string & K}`]: Original[K] }
It creates a new type where each key from Original is renamed by prefixing new_ to the original key name.
Click to reveal answer
advanced
Can you use conditional logic inside the as clause for key remapping?
Yes, you can use conditional types to rename keys selectively or exclude keys by mapping them to never.
Click to reveal answer
intermediate
What happens if you map a key to never in the as clause?
That key is removed from the resulting type, effectively filtering out keys.
Click to reveal answer
What is the purpose of the as clause in TypeScript mapped types?
ATo add new keys
BTo rename keys during mapping
CTo change the value types
DTo delete the entire type
How do you exclude a key from a mapped type using the as clause?
AMap the key to <code>undefined</code>
BUse <code>as void</code>
CUse <code>as null</code>
DMap the key to <code>never</code>
Which syntax correctly renames keys in a mapped type?
A{ [K in keyof T as NewKey]: T[K] }
B{ [K in keyof T]: T[K] as NewKey }
C{ [K as NewKey in keyof T]: T[K] }
D{ NewKey in keyof T: T[K] }
What type of keys can you create using template literal types with as clause?
AKeys with dynamic string patterns
BOnly numeric keys
COnly boolean keys
DKeys with fixed names only
If you want to keep the original key name in a remapping, what should you do?
AUse <code>as string</code>
BUse <code>as never</code>
CUse <code>as K</code>
DOmit the <code>as</code> clause
Explain how the as clause works in TypeScript key remapping and give an example.
Think about how you can change key names while keeping values.
You got /3 concepts.
    Describe how to remove keys from a mapped type using the as clause.
    Consider what happens when a key maps to never.
    You got /3 concepts.