TypeScript Object Type readonly Properties (original) (raw)

Last Updated : 23 Jan, 2025

In TypeScript, the readonly modifier ensures that a property can be assigned a value only once during initialization and cannot be changed thereafter.

class ReadonlyExample { readonly name: string;

constructor(name: string) { this.name = name; }

getName(): string { return this.name; } }

const obj = new ReadonlyExample("John"); console.log(obj.getName());

`

**Output:

John

**More Examples of TypeScript Object Type readonly Properties

Immutable Point Coordinates

JavaScript ``

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

const p1: Point = { x: 10, y: 20 }; console.log(Point coordinates: (${p1.x}, ${p1.y}));

// p1.x = 15; // Error: Cannot assign to 'x' because it is a read-only property.

``

**Output:

Point coordinates: (10, 20)

**Readonly Array of Numbers

JavaScript `

const numbers: ReadonlyArray = [1, 2, 3, 4, 5]; console.log(numbers);

// numbers.push(6); // Error: Property 'push' does not exist on type 'readonly number[]'.

`

**Output:

[1, 2, 3, 4, 5]

Readonly Property in a Class

JavaScript ``

class Car { readonly make: string; readonly model: string;

constructor(make: string, model: string) { this.make = make; this.model = model; }

getCarInfo(): string { return ${this.make} ${this.model}; } }

const myCar = new Car('Toyota', 'Corolla'); console.log(myCar.getCarInfo());

// myCar.make = 'Honda'; // Error: Cannot assign to 'make' because it is a read-only property.

``

**Output:

Toyota Corolla

Best Practices for Using TypeScript readonly Properties: