What You'll Learn
You'll learn how to use mapped types together with template literal types to automatically generate related property names like 'onChange' from 'value', creating type-safe patterns for forms, events, and configuration objects.
The Core Idea
In many JavaScript patterns, you have groups of properties that follow a naming convention. For example, if you have a value property, you might also have an onChange handler. If you have a username field, you might have an onUsernameChange callback.
Instead of manually typing each pair, you can generate property names programmatically using mapped types that iterate over keys and template literals that transform them.
Think of it like a naming machine: feed it base property names, and it stamps out related names following your pattern automatically.
Combining Mapped Types with Template Literals
Here's the pattern in action:
type FormFields = {
username: string;
email: string;
age: number;
};
// Generate 'onChange' handlers for each field
type FormHandlers = {
[K in keyof FormFields as `on${Capitalize<K>}Change`]: (value: FormFields[K]) => void;
};
// Result type is:
// {
// onUsernameChange: (value: string) => void;
// onEmailChange: (value: string) => void;
// onAgeChange: (value: number) => void;
// }
What's happening:
[K in keyof FormFields]iterates over each keyasremaps each key using a template literal`on${Capitalize<K>}Change`creates the new property nameFormFields[K]preserves the correct value type for each handler
Practical Example: Form with Generated Handlers
type Config = {
maxRetries: number;
timeout: number;
enableLogging: boolean;
};
type ConfigSetters = {
[K in keyof Config as `set${Capitalize<K>}`]: (newValue: Config[K]) => void;
};
// Result:
// {
// setMaxRetries: (newValue: number) => void;
// setTimeout: (newValue: number) => void;
// setEnableLogging: (newValue: boolean) => void;
// }
This pattern ensures that if you add a new property to Config, the corresponding setter type appears automatically—no manual synchronization needed.
Key Takeaway: By combining mapped types with template literal types and key remapping (as), you can dynamically generate entire families of related property names that stay synchronized with your base types, eliminating repetition and keeping your types DRY.