typescript / intermediate
Snippet
Transforming Property Names with Mapped Types and Key Remapping
Mapped types can iterate over object keys and use template literal types combined with the 'as' keyword to dynamically rename property keys at compile time. This snippet turns object keys like 'theme' into type-safe callback names like 'onThemeChanged'.
snippet.ts
typescript
1
2
3
4
5
6
7
8
9
10
type EventHandlers<T extends Record<string, any>> = {[K in keyof T as `on${Capitalize<string & K>}Changed`]?: (newValue: T[K]) => void;};interface UserSettings {theme: string;notifications: boolean;}type UserSettingsListeners = EventHandlers<UserSettings>;
Breakdown
1
[K in keyof T as `on${Capitalize<string & K>}Changed`]?: (newValue: T[K]) => void;
Iterates over key K, capitalizes its name, prepends 'on', appends 'Changed', and assigns a matching value callback type.
2
type UserSettingsListeners = EventHandlers<UserSettings>;
Generates an interface with optional listeners: onThemeChanged and onNotificationsChanged.