0
0
Typescriptprogramming~3 mins

Why Basic mapped type syntax in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change every property in a type with just one simple rule?

The Scenario

Imagine you have an object with many properties, and you want to create a new object where each property has a different type or is optional. Doing this by hand means writing out each property and its new type one by one.

The Problem

This manual way is slow and boring. If the object has many properties, you might make mistakes or forget to update some when the original object changes. It's hard to keep track and easy to get tired.

The Solution

Basic mapped type syntax lets you write a simple rule that automatically changes every property in an object type. You write the rule once, and TypeScript applies it to all properties, saving time and avoiding errors.

Before vs After
Before
type User = { name: string; age: number; };
type PartialUser = { name?: string; age?: number; };
After
type User = { name: string; age: number; };
type PartialUser = { [K in keyof User]?: User[K] };
What It Enables

This lets you quickly create new types based on existing ones, changing all properties at once with a clear, simple rule.

Real Life Example

When building a form, you might want a version of your data type where all fields are optional so users can fill in only some parts. Mapped types make this easy and safe.

Key Takeaways

Manual property changes are slow and error-prone.

Mapped types apply changes to all properties automatically.

This saves time and keeps your code consistent.