Event Handler Type Generation
What you'll learn: How to automatically generate type-safe event handler function types from a component's property names using mapped types and template literals.
The Problem We're Solving
Imagine you have a component with properties like username, email, and isActive. You want event handlers named onUsernameChange, onEmailChange, and onIsActiveChange. Writing these types manually is tedious and error-prone. What if properties change? You'd need to update handlers everywhere.
The Solution: Automated Handler Types
By combining mapped types with template literal types, TypeScript can generate handler names and their signatures automatically from your data model:
type User = {
username: string;
email: string;
isActive: boolean;
};
type EventHandlers<T> = {
[K in keyof T as `on${Capitalize<string & K>}Change`]: (value: T[K]) => void;
};
type UserHandlers = EventHandlers<User>;
// Result:
// {
// onUsernameChange: (value: string) => void;
// onEmailChange: (value: string) => void;
// onIsActiveChange: (value: boolean) => void;
// }
How It Works
[K in keyof T]iterates over each property name inTas \on${Capitalize<string & K>}Change`` remaps each key to a handler name(value: T[K]) => voidcreates a function type that accepts the property's value type- The
string & KensuresKis treated as a string forCapitalize
This pattern is powerful for React props, event systems, and form libraries where handler naming follows conventions.
Key Takeaway: Template literal types in mapped type key remapping let you automatically generate entire families of related function types from a single source of truth, eliminating manual repetition and keeping handler types synchronized with your data model.