Key Remapping (as)

Renaming keys dynamically during a mapped type loop.

TypeScript5 min readConcept 31 of 54

Changing Keys on the Fly

In TypeScript 4.1+, you can change the actual name of a key while you are looping over it in a mapped type.

By using the as keyword inside the bracket notation, you can transform the key, format it, or even filter it out completely.

Getters, Setters, and Filtering

If you have a User type with { name: string; age: number }, and you want to generate a store object with { getName: () => string; getAge: () => number }, key remapping makes it trivial.

It allows you to derive highly complex, correctly typed APIs directly from simple base types.

Syntax

typescript type User = { name: string; age: number }; // Add 'get' prefix, capitalize the original key, and return a function. type Getters<T> = { [K in keyof T as get${Capitalize<string & K>}]: () => T[K]; }; type UserGetters = Getters<User>; // { // getName: () => string; // getAge: () => number; // }

Try it

Watch the as keyword physically rename keys dynamically during a mapped type loop, converting plain properties into prefixed getter functions.

Auto-Remapping in progress...
type User = {
  id: number;
  name: string;
};
type Getters<T> = {
[K in keyof Tas`get${Capitalize<string & K>}`]: () => T[K];
};
Remap Pipeline
Loop: 1/2
as keyword active
1. Capitalize<K>
"id""id"
Building...

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1How do you completely drop a key from a mapped type using key remapping?

Remember this

  • Key remapping uses the syntax [K in keyof T as NewKeyType].
  • It is incredibly powerful when combined with Template Literal Types.
  • Remapping a key to never removes it from the final type.
  • It avoids the need for creating multiple boilerplate interfaces for getters/setters.

Done with this concept?

Mark it complete to track your progress. No login needed.