A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/typescript/typescript-object-type-readonly-properties/ below:

TypeScript Object Type readonly Properties

TypeScript Object Type readonly Properties

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.

JavaScript
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<number> = [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:

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4