← Back to TypeScript Course | Chapter 8: Advanced Types | Lesson 12 of 20

Utility Types - Readonly

Readonly<T> makes every property of an object type readonly. This prevents reassignment of those properties after initialization.

Basic Readonly

Readonly<T> produces a version of an object type whose properties can no longer be reassigned, giving the same compile-time protection as writing the readonly modifier on every property by hand.

Example: Basic Readonly

typescript
interface Point {
  x: number;
  y: number;
}
const p: Readonly<Point> = { x: 1, y: 2 };
console.log(p);

Readonly Arrays

Readonly can also be applied to array types to prevent mutation through methods such as push, pop, or splice, while still allowing the array's existing elements to be freely read.

Example: Readonly Arrays

typescript
const values: ReadonlyArray<number> = [1, 2, 3];
console.log(values[0]);

Readonly Objects

Readonly is useful for objects that should be treated as fixed configuration or reference data — values that are meant to be read throughout the program's lifetime but never modified after creation.

Example: Readonly Objects

typescript
interface AppConfig {
  apiUrl: string;
}
const config: Readonly<AppConfig> = { apiUrl: "https://api.example.com" };
console.log(config.apiUrl);

Readonly and Nested Objects

Readonly only applies to the top-level properties of an object; any nested objects inside it need their own separate Readonly wrapping if you want their properties protected too.

Example: Readonly and Nested Objects

typescript
interface Address {
  city: string;
}
interface Person {
  name: string;
  address: Address;
}
const p: Readonly<Person> = { name: "Ravi", address: { city: "Patna" } };
p.address.city = "Delhi";
console.log(p.address.city);

When to Use Readonly

Readonly<T> is useful whenever callers should be able to inspect data freely but should never be able to reassign its properties, which helps prevent accidental shared-state bugs.

Example: When to Use Readonly

typescript
interface Constants {
  PI: number;
}
const MATH: Readonly<Constants> = { PI: 3.14159 };
console.log(MATH.PI);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.