Course contentsShow
← TypeScript
Lesson 743 of 1,79617. Mapped TypesFree lesson

The Default Behavior: Preserving Modifiers

By default, mapped types preserve readonly and optional modifiers from the source type.

The Default Behavior: Preserving Modifiers

What you'll learn: You'll discover how mapped types automatically keep readonly and optional (?) modifiers from the original type unless you explicitly change them.


When you create a mapped type, TypeScript doesn't strip away the special properties of the source type's fields. If a property was readonly in the original type, it stays readonly in the mapped type. If it was optional, it remains optional. This is the default preservation behavior.

Understanding Preservation

Think of mapped types like photocopiers. When you copy a document, the copier preserves the formatting, fonts, and layout by default. Similarly, mapped types preserve modifiers unless you actively tell them to do otherwise.

Consider this example:

type User = {
  readonly id: number;
  name?: string;
  email: string;
};

type MappedUser = {
  [K in keyof User]: boolean;
};

Even though we're transforming all property types to boolean, the modifiers stay intact. The result is:

// MappedUser becomes:
type MappedUser = {
  readonly id: boolean;
  name?: boolean;
  email: boolean;
}

Notice that id kept its readonly modifier and name kept its optional ? modifier. We only changed the value types, not the modifiers.

Why This Matters

This default behavior prevents accidental loss of important constraints. When you're transforming types for utility purposes (like converting all properties to strings for serialization), you usually want to maintain whether fields are read-only or optional.

If you want to change modifiers, you'll use + or - syntax, which you learned in previous lessons.

Key Takeaway: Mapped types preserve readonly and optional modifiers from the source type by default, maintaining the original type's constraints during transformation.