Advertisement
Intermediate TypeScript, Mapped Types

How does 'key remapping' with the 'as' clause work in a mapped type?

Short answer

Adding `as NewKeyExpression` after the `K in keyof T` clause lets you transform the resulting property NAME (not just its value type) — commonly combined with template literal types to systematically rename every key, like generating getter/setter method names from data…

Save TypeScript mock interview
Advertisement
AModel answer
Adding `as NewKeyExpression` after the `K in keyof T` clause lets you transform the resulting property NAME (not just its value type) — commonly combined with template literal types to systematically rename every key, like generating getter/setter method names from data properties.
type EventHandlers<T> = {
  [K in keyof T as `on${Capitalize<string & K>}Change`]: (value: T[K]) => void
};
interface FormFields { name: string; age: number; }
type Handlers = EventHandlers<FormFields>;
// { onNameChange: (value: string) => void; onAgeChange: (value: number) => void }
Real-world example
Auto-generating a consistent set of event-handler prop names from a data model, avoiding manual duplication and drift.
Likely follow-ups
  • Can the 'as' clause also be used to conditionally OMIT a key entirely from the result?
Related topics