Intermediate LevelJavaScript & TypeScript
What are mapped types with key remapping in TypeScript (as clause in mapped types)?
❓ Interview Prompt: Explain mapped type syntax ([K in keyof T]), property modifiers (+/- readonly/?), and key remapping with as clause.
Mapped Types build new object types by iterating over keys of an existing type.
Syntax:
type ReadonlyObject<T> = { readonly [K in keyof T]: T[K] };
Key Remapping (as Clause):
TypeScript allows remapping keys during mapping using the as clause and template literal types:
•
Filter out keys by remapping to
never.•
Modify key names (e.g. adding
get prefix to key names).Code Implementation Example
typescript
interface Person {
name: string;
age: number;
}
// Generate Getters object type using key remapping
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
type PersonGetters = Getters<Person>;
// Equivalent to: { getName: () => string; getAge: () => number; }
// Filter out non-string keys
type RemoveAge<T> = {
[K in keyof T as K extends 'age' ? never : K]: T[K]
};💡Key remapping with as clause generating getter method interfaces.
🎯 Interview Key Takeaway
Mapped types transform object properties. Use the as clause to rename or filter keys dynamically.
#TypeScript#Mapped Types#Key Remapping#Intermediate
Back to all JavaScript & TypeScript Questions→