Typescript Foundations / Utility Types

Readonly

🔒 Readonly<T>

Readonly<T> is a built-in utility type that makes all properties of a type read-only.

Once an object is created, its properties cannot be changed.

🔹 Example

type User = {
  name: string;
  age: number;
};

const user: Readonly<User> = {
  name: "Bhaskar",
  age: 25
};

console.log(user.name); // Bhaskar

user.name = "Rahul"; // ❌ Error
user.age = 30;       // ❌ Error

Without Readonly, the properties can be changed:

user.name = "Rahul"; // ✅

Readonly<User> effectively makes the type:

{
  readonly name: string;
  readonly age: number;
}

💡 Common Use

Readonly<T> is useful for configuration objects, constants, and data that should not be modified after creation.

Remember: Readonly<T> → Makes every property in T read-only.