0
0
Typescriptprogramming~3 mins

Why Mapped type modifiers (readonly, optional) in Typescript? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could change all your type properties at once without rewriting a single line?

The Scenario

Imagine you have a big list of user settings in your app. You want to make some settings unchangeable (readonly) and others optional, but you have to write a new type for each variation by hand.

The Problem

Writing many versions of similar types manually is slow and tiring. It's easy to make mistakes or forget to update all versions when your settings change. This leads to bugs and wasted time.

The Solution

Mapped type modifiers let you create new types by changing properties all at once. You can add readonly or make properties optional automatically, saving time and avoiding errors.

Before vs After
Before
type UserSettings = { name: string; age: number };
type ReadonlyUserSettings = { readonly name: string; readonly age: number; };
After
type UserSettings = { name: string; age: number };
type ReadonlyUserSettings = { readonly [K in keyof UserSettings]: UserSettings[K] };
What It Enables

You can quickly create flexible and safe types that adapt automatically as your data changes.

Real Life Example

When building a form, you can make all fields optional for editing, or readonly for review, without rewriting types for every form variation.

Key Takeaways

Manual type changes are slow and error-prone.

Mapped type modifiers automate adding readonly or optional to all properties.

This keeps your code DRY and easier to maintain.