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

Readonly vs const

const prevents variable reassignment; Readonly prevents property mutation—they serve different purposes and combine well.

Readonly vs const

You'll learn how const and Readonly serve different purposes and work together to prevent different kinds of changes.

The Core Difference

In TypeScript, const prevents variable reassignment, while Readonly prevents property mutation. They operate at completely different levels:

  • const is a JavaScript keyword that protects the binding (the variable itself)
  • Readonly is a TypeScript utility type that protects the contents (object properties)

Think of it like a locked box: const locks the box shut so you can't swap it for a different box, but Readonly locks the items inside the box so you can't change them.

How They Work Separately

const user = { name: "Alice", age: 30 };
user = { name: "Bob", age: 25 }; // ❌ Error: Cannot reassign const
user.age = 31; // ✅ Allowed! const doesn't protect properties

type ReadonlyUser = Readonly<{ name: string; age: number }>;
let userData: ReadonlyUser = { name: "Alice", age: 30 };
userData = { name: "Bob", age: 25 }; // ✅ Allowed! let can be reassigned
userData.age = 31; // ❌ Error: Cannot assign to 'age' (readonly)

Why Combine Them

For maximum immutability, use both together:

const config: Readonly<{ port: number; host: string }> = {
  port: 3000,
  host: "localhost"
};

config = { port: 8080, host: "0.0.0.0" }; // ❌ const prevents reassignment
config.port = 8080; // ❌ Readonly prevents mutation

Now your configuration is truly immutable—you can't swap the entire object or modify its properties.

Key Takeaway: const and Readonly protect different things—the variable binding vs the object's properties. Use const for variables you won't reassign, Readonly for objects whose properties shouldn't change, and combine them for complete immutability.