Prefixing and Suffixing Object Keys
You'll learn how to systematically transform all keys in an object type by adding text before or after them using mapped types and template literals.
The Core Idea
Imagine you have an object type representing user properties like name, email, and age. Sometimes you need to create a new type where every property has a prefix (like get_name, get_email) or suffix (like name_formatted, email_formatted). Doing this manually would be tedious and error-prone.
By combining mapped types with template literal types and key remapping, you can automatically transform all keys in a type at once.
How It Works
You create a mapped type that iterates over the original keys, then uses as to rename each key with a template literal that adds your prefix or suffix:
// Prefixing keys
type WithPrefix<T, Prefix extends string> = {
[K in keyof T as `${Prefix}${K & string}`]: T[K]
};
// Suffixing keys
type WithSuffix<T, Suffix extends string> = {
[K in keyof T as `${K & string}${Suffix}`]: T[K]
};
type User = {
name: string;
email: string;
age: number;
};
// Result: { get_name: string; get_email: string; get_age: number }
type UserGetters = WithPrefix<User, 'get_'>;
// Result: { name_old: string; email_old: string; age_old: number }
type OldUserFields = WithSuffix<User, '_old'>;
The K & string intersection ensures TypeScript treats the key as a string type for template literal compatibility.
Common Use Cases
This pattern shines when building type-safe wrappers around APIs, creating getter/setter types, versioning fields, or adding namespacing to avoid property collisions:
type Getters<T> = WithPrefix<T, 'get'>;
type Setters<T> = WithPrefix<T, 'set'>;
Key Takeaway: Mapped types with template literal key remapping let you systematically add prefixes or suffixes to all object keys, creating powerful type transformations without manual repetition.