Key remapping
Concept and syntax
An as clause in a mapped type can rename keys. String template operations require suitable string keys; string & K excludes non-string keys here. The implementation still needs to create the renamed properties.
Working example
Save each snippet separately as main.ts in a fresh directory with TypeScript 5.8.3. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts and run accepted snippets with node main.js. Type aliases are erased; assignments and diagnostic checks demonstrate the type relations, not the printed output alone.
type Getters<T>={[K in keyof T as `get_${string & K}`]:()=>T[K]}; type G=Getters<{count:number}>;const g:G={get_count:()=>4}; console.log(g.get_count());Expected output:
4Common mistake
Intentionally invalid; compile separately and do not execute.
type Getters<T>={[K in keyof T as `get_${string & K}`]:()=>T[K]}; type G=Getters<{count:number}>;const g:G={count:()=>4};Expected diagnostic: TS2353. The mapped key is get_count, not count.
Practice and recap
Add a second field and implement its getter.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Key remapping — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Key remapping is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Getters<T>={[K in keyof T as `get_${string & K}`]:()=>T[K]}; type G=Getters<{count:number}>;const g:G={get_count:()=>4}; console.log(g.get_count());Which diagnostic and explanation match the rejected example under the lesson settings?
type Getters<T>={[K in keyof T as `get_${string & K}`]:()=>T[K]}; type G=Getters<{count:number}>;const g:G={count:()=>4};What is the type of Getters<{label:string}>["get_label"]?