Discover how a single line of code can replace dozens of repetitive property definitions!
Why Mapped type with template literals in Typescript? - Purpose & Use Cases
Imagine you have many object properties and you want to create new property names by adding prefixes or suffixes manually for each one.
For example, if you have properties like name and age, you want to create getName, setName, getAge, setAge by hand.
Doing this manually means writing repetitive code for each property, which is slow and easy to make mistakes.
It's hard to keep track of all variations and update them if the original properties change.
Mapped types with template literals let you automatically create new property names by combining strings and existing keys.
This means you write one simple rule, and TypeScript generates all the new properties for you, saving time and avoiding errors.
interface Person {
name: string;
age: number;
}
interface PersonMethods {
getName(): string;
setName(value: string): void;
getAge(): number;
setAge(value: number): void;
}type Person = {
name: string;
age: number;
};
type PersonMethods = {
[K in keyof Person as `get${Capitalize<string & K>}`]: () => Person[K];
} & {
[K in keyof Person as `set${Capitalize<string & K>}`]: (value: Person[K]) => void;
};You can create flexible, consistent, and scalable object types that automatically adapt when your base properties change.
When building a form library, you can automatically generate getter and setter methods for each form field without writing each one manually.
Manual property renaming is repetitive and error-prone.
Mapped types with template literals automate property name creation.
This leads to cleaner, safer, and easier-to-maintain code.