What are readonly properties in TypeScript?

Beginner

Answer

Readonly properties can only be assigned during initialization and cannot be modified afterward:

interface Point {
  readonly x: number;
  readonly y: number;
}

const point: Point = { x: 10, y: 20 };
// point.x = 30; // Error: Cannot assign to 'x' because it is read-only

// Readonly arrays
const readonlyArray: readonly number[] = [1, 2, 3];
// readonlyArray.push(4); // Error: Property 'push' does not exist

// ReadonlyArray type
const numbers: ReadonlyArray<number> = [1, 2, 3];