typescript / intermediate
Snippet
Constructing Event Names using Template Literal Types
Template literal types generate string unions by combining string templates with intrinsics like `Capitalize`. This allows creating type-safe dynamic property names such as event listeners automatically derived from base names.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
11
type EventKind = "click" | "hover" | "focus";type EventHandlerName = `on${Capitalize<EventKind>}`;type EventRegistry = {[K in EventHandlerName]?: () => void;};const handlers: EventRegistry = {onClick: () => console.log("Clicked"),onHover: () => console.log("Hovered")};
Breakdown
1
type EventHandlerName = `on${Capitalize<EventKind>}`;
Creates string literal types 'onClick' | 'onHover' | 'onFocus' using string interpolation and capitalization.
2
type EventRegistry = { [K in EventHandlerName]?: () => void; };
Uses a mapped type over the generated string union to define optional callback functions.
3
const handlers: EventRegistry = { ... };
Ensures handler objects strictly conform to the generated event property names.