Course contentsShow
← TypeScript
Lesson 669 of 1,79616. Utility TypesFree lesson

The Readonly<T> Utility

Makes all properties of type T readonly, preventing reassignment and enforcing immutability at compile time.

The Readonly<T> Utility

What you'll learn: How to use Readonly<T> to prevent property reassignment and enforce immutability at compile time.

What Is Readonly<T>?

Readonly<T> is a built-in utility type that takes any type T and transforms all of its properties into readonly properties. This means once an object is created, TypeScript will prevent you from reassigning any of its properties—acting like a compile-time lock.

Think of it like sealing an envelope: you can read what's inside, but you can't change the contents once it's sealed.

Basic Syntax

interface User {
  id: number;
  name: string;
  email: string;
}

const user: Readonly<User> = {
  id: 1,
  name: "Alice",
  email: "alice@example.com"
};

// ❌ Error: Cannot assign to 'name' because it is a read-only property
user.name = "Bob";

// ✅ Reading is perfectly fine
console.log(user.name); // "Alice"

Why Use Readonly<T>?

Readonly<T> is useful when you want to pass data around your application but guarantee it won't be mutated. This is particularly valuable in functional programming patterns, configuration objects, or when working with state that shouldn't change after initialization.

function processUser(user: Readonly<User>): void {
  // TypeScript prevents accidental mutations here
  // user.id = 999; // ❌ Error!
  console.log(`Processing ${user.name}`);
}

Important Limitation

Readonly<T> only affects the top level properties. Nested objects remain mutable unless you apply Readonly<T> to them as well.

type Config = Readonly<{
  server: { port: number };
}>;

const config: Config = { server: { port: 3000 } };

// ❌ Can't reassign server
// config.server = { port: 4000 };

// ⚠️ But nested properties ARE still mutable!
config.server.port = 4000; // ✅ This works

Key Takeaway: Readonly<T> makes all top-level properties of type T readonly, preventing reassignment and catching mutation bugs at compile time—but remember it's shallow, not deep.