Mapping Keys to Template Literal Types
What you'll learn: How to transform object property names using template literal types inside mapped types.
The Core Idea
When you combine mapped types with template literal types, you can iterate over an object's keys and transform each key name according to a string pattern. This lets you create entirely new object shapes where property names follow a specific naming convention—like adding prefixes, suffixes, or converting between naming styles.
How It Works
You use the as clause in a mapped type to remap keys, applying template literal transformations:
type AddPrefix<T> = {
[K in keyof T as `get${Capitalize<K & string>}`]: T[K]
};
type User = {
name: string;
age: number;
};
type Getters = AddPrefix<User>;
// Result:
// {
// getName: string;
// getAge: number;
// }
Here, K in keyof T iterates over each key, and as transforms it using a template literal that capitalizes the key and adds "get" as a prefix.
Practical Applications
Converting to event names:
type ToEventHandlers<T> = {
[K in keyof T as `on${Capitalize<K & string>}`]: (value: T[K]) => void
};
type State = {
count: number;
visible: boolean;
};
type Handlers = ToEventHandlers<State>;
// Result:
// {
// onCount: (value: number) => void;
// onVisible: (value: boolean) => void;
// }
The K & string pattern ensures we're working with string keys only, avoiding issues with symbol or numeric keys.
Key Takeaway: Mapping keys to template literal types lets you programmatically rename properties across an entire object type, creating type-safe naming conventions like getters, setters, or event handlers without manual duplication.