What it is and why to use it
Key remapping changes the property names produced by a mapped type. The as clause calculates a new key while the original K remains available for looking up its value. This is useful for describing an adapter API derived from an existing data model.
Common mistakes and limitations
Remapping a type does not rename real object keys. Symbol keys and numeric keys need a deliberate policy. Names can also collide after a transformation, so design the naming convention carefully.
Run this example
Use TypeScript 5.8 or later with strict checking and an ES2022 target. Save each complete example independently as example.ts, compile it, then run the generated JavaScript with a compatible Node.js installation. Compiler-only options below affect checking; they do not add runtime validation.
Terminal — compile and run
npx tsc example.ts --strict --target ES2022 --module commonjs
node example.jsSyntax
type Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] };Examples
Renaming Keys in Mapped Types
Standalone TypeScript 5.8+ example; expected output is explained below.
type Getters<T> = {
[K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
};
type Person = { name: string; score: number };
const getters: Getters<Person> = {
getName: () => "John", getScore: () => 87
};
console.log(getters.getName() + ": " + getters.getScore());- keyof Person supplies name and score.
- The template literal and Capitalize produce getName and getScore; string & K limits this naming recipe to string keys.
- Each method returns the corresponding original property type. The implementation is written explicitly because a type does not create runtime methods.
- Expected output: John: 87
Best practices
- Remapping a type does not rename real object keys. Symbol keys and numeric keys need a deliberate policy. Names can also collide after a transformation, so design the naming convention carefully.
- Keep external-input validation separate from compile-time type descriptions.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook