Course contentsShow
← TypeScript
Lesson 305 of 1,7967. ObjectsFree lesson

Combining Optional and Readonly

Apply both ? and readonly modifiers together for immutable optional properties.

Combining Optional and Readonly

You'll learn how to apply both the ? (optional) and readonly modifiers to the same property, creating immutable properties that may or may not exist.

The Core Idea

In TypeScript, you can use both modifiers on a single property. When you combine readonly and ?, you create a property that:

  1. May or may not be present on the object (? makes it optional)
  2. Cannot be reassigned once set (readonly prevents mutation)

Think of it like a safety deposit box that might be empty (?), but if it contains something, that content is locked in place (readonly).

Syntax and Behavior

type User = {
  readonly id: number;           // Required and immutable
  readonly email?: string;       // Optional and immutable
  name?: string;                 // Optional but mutable
};

const user: User = { id: 123 };  // Valid: email is optional

user.id = 456;        // ❌ Error: Cannot assign (readonly)
user.email = "a@b.c"; // ❌ Error: Cannot assign (readonly)
user.name = "Alice";  // ✅ Allowed: not readonly

The order doesn't matter—readonly email? and email?: readonly aren't valid, but readonly email?: is the correct syntax.

Real-World Use Case

type Config = {
  readonly apiKey: string;
  readonly endpoint?: string;     // Optional default endpoint
  retryCount?: number;            // Optional and adjustable
};

const config: Config = { 
  apiKey: "secret123" 
};

// config.endpoint = "...";       // ❌ Can't set after creation
// config.apiKey = "new";         // ❌ Can't change key
config.retryCount = 5;            // ✅ Can modify this one

Key Takeaway: Use readonly and ? together when a property is optional during creation but must not change if it exists—perfect for configuration values with optional defaults.