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

Adding and Removing readonly with + and -

Use +readonly and -readonly to explicitly add or remove readonly modifiers in mapped types.

Adding and Removing readonly with + and -

What You'll Learn

You'll learn how to explicitly control whether properties should be readonly using the +readonly and -readonly modifier syntax in mapped types.


The Core Idea

In mapped types, you can use +readonly to add the readonly modifier and -readonly to remove it. The + is optional (writing readonly alone defaults to adding it), but using explicit + and - makes your intent crystal clear and enables dynamic control.

Think of it like volume controls: + turns up the restriction (makes properties readonly), while - turns it down (makes them mutable again).


The Syntax

// Adding readonly explicitly
type AddReadonly<T> = {
  +readonly [K in keyof T]: T[K];
};

// Removing readonly explicitly
type RemoveReadonly<T> = {
  -readonly [K in keyof T]: T[K];
};

// Just "readonly" is the same as "+readonly"
type ImplicitPlus<T> = {
  readonly [K in keyof T]: T[K]; // Same as +readonly
};

Practical Example

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

// Make ALL properties readonly
type FullyReadonly<T> = {
  +readonly [K in keyof T]: T[K];
};

type ReadonlyUser = FullyReadonly<User>;
// { readonly id: number; readonly name: string; readonly email: string; }

// Remove ALL readonly modifiers
type Mutable<T> = {
  -readonly [K in keyof T]: T[K];
};

type MutableUser = Mutable<User>;
// { id: number; name: string; email: string; }

The minus operator strips readonly even from properties that were originally readonly, giving you full control over mutability.


Key Takeaway:
Use +readonly to explicitly add readonly modifiers and -readonly to explicitly remove them in mapped types, giving you precise control over property mutability transformations.