0
0
Typescriptprogramming~3 mins

Why Mapped type with template literals in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a single line of code can replace dozens of repetitive property definitions!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
interface Person {
  name: string;
  age: number;
}

interface PersonMethods {
  getName(): string;
  setName(value: string): void;
  getAge(): number;
  setAge(value: number): void;
}
After
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;
};
What It Enables

You can create flexible, consistent, and scalable object types that automatically adapt when your base properties change.

Real Life Example

When building a form library, you can automatically generate getter and setter methods for each form field without writing each one manually.

Key Takeaways

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.