Course contentsShow
← TypeScript
Lesson 845 of 1,79619. Template Literal TypesFree lesson

Event Handler Type Generation

Build event handler types automatically from property names using mapped types and template literals.

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

  1. [K in keyof T] iterates over each property name in T
  2. as \on${Capitalize<string & K>}Change`` remaps each key to a handler name
  3. (value: T[K]) => void creates a function type that accepts the property's value type
  4. The string & K ensures K is treated as a string for Capitalize

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.