Key-name generation
Concept and syntax
Template literal names can be combined with mapped key remapping to derive event or getter contracts from property names. Capitalize transforms the first character of a string type. Use a string-key restriction to avoid symbol keys.
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 Events<T>={[K in keyof T as `on${Capitalize<string & K>}`]:(value:T[K])=>void}; type E=Events<{count:number}>;const e:E={onCount:n=>console.log(n+1)}; e.onCount(4);Expected output:
5Common mistake
Intentionally invalid; compile separately and do not execute.
type Events<T>={[K in keyof T as `on${Capitalize<string & K>}`]:(value:T[K])=>void}; type E=Events<{count:number}>;const e:E={onCount:n=>console.log(n)}; e.onCount("4");Expected diagnostic: TS2345. onCount retains the number payload from count.
Practice and recap
Add a string field and derive its event handler.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Key-name generation — knowledge check
Check the type transformation, trace output, diagnose a rejected example, and apply the concept to a new case.
Which statement about Key-name generation is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
type Events<T>={[K in keyof T as `on${Capitalize<string & K>}`]:(value:T[K])=>void}; type E=Events<{count:number}>;const e:E={onCount:n=>console.log(n+1)}; e.onCount(4);Which diagnostic and explanation match the rejected example under the lesson settings?
type Events<T>={[K in keyof T as `on${Capitalize<string & K>}`]:(value:T[K])=>void}; type E=Events<{count:number}>;const e:E={onCount:n=>console.log(n)}; e.onCount("4");What handler name is generated from a key named title?