Quick Answer
Compile-time immutability enforcement
Understanding the Issue
The readonly modifier prevents assignment to properties outside the constructor. For arrays and objects, it prevents reassignment but not mutation of content.
The Problem
This code demonstrates the issue:
Typescript
Error
// Problem: Accidental reassignment
interface Point {
x: number;
y: number;
}
const p: Point = { x: 1, y: 2 };
p.x = 3; // Allowed
The Solution
Here's the corrected code:
Typescript
Fixed
// Solution 1: Readonly interface
interface Point {
readonly x: number;
readonly y: number;
}
// Solution 2: Readonly utility type
const p: Readonly<Point> = { x: 1, y: 2 };
p.x = 3; // Error
// For arrays:
const nums: readonly number[] = [1, 2, 3];
nums[0] = 4; // Error
Key Takeaways
Use readonly to enforce immutability at compile time.