TypeScript - 只讀屬性



TypeScript 提供了 readonly 關鍵字,用於將類、型別或介面中的屬性設為只讀。 只讀屬性 可以從類外部訪問,但其值不能被修改。

透過使用只讀屬性,您可以確保沒有人可以在物件外部修改屬性,但他們可以讀取屬性的值。

語法

要在 TypeScript 中定義只讀屬性,我們用 readonly 關鍵字作為屬性名的字首。

readonly propName: type;

其中,

  • 在上述語法中,**'readonly'** 是一個關鍵字。

  • **'propName'** 是隻讀屬性的屬性名。

  • **'type'** 是隻讀屬性的屬性型別。

封裝實體可以在 TypeScript 中是 介面

您可以用所需的只讀屬性名稱替換 propertyName,用適當的資料型別替換 type

帶介面的只讀屬性

介面用於定義物件的原型。我們可以在介面中定義只讀屬性。讓我們透過下面的例子來理解它。

示例

在下面的程式碼中,我們定義了包含 model、year 和 fuel 屬性的 Car 介面。這裡,fuel 屬性是隻讀的,它只能在建立物件時初始化,但在建立物件後不能更改。

之後,我們建立了 Car 型別的物件並初始化了所有屬性。

您可以嘗試更改 car 物件的 fuel 屬性的值,並觀察錯誤。

//  Defining the interface for the car
interface Car {
    model: string;
    year: number;
    readonly fuel: string;
}

// Defining the car object
let car: Car = {
    model: 'BMW',
    year: 2019,
    fuel: 'petrol'
}

console.log(car.model);
console.log(car.year);
console.log(car.fuel);

// Error: Cannot assign to 'fuel' because it is a read-only property.
// car.fuel = 'diesel';

編譯後,它將生成以下 JavaScript 程式碼。

// Defining the car object
let car = {
    model: 'BMW',
    year: 2019,
    fuel: 'petrol'
};
console.log(car.model);
console.log(car.year);
console.log(car.fuel);
// Error: Cannot assign to 'fuel' because it is a read-only property.
// car.fuel = 'diesel';

輸出

上面示例程式碼的輸出如下:

BMW
2019
petrol

帶類的只讀屬性

類也可以包含類似於介面的只讀屬性。只讀屬性的值可以在建立物件時在 constructor() 方法中初始化。您不能使用類例項更改類的只讀屬性的值。

示例

在下面的程式碼中,我們定義了包含 model 和 price 屬性的 car 類。它還包含 'type' 只讀屬性。

在 constructor() 方法中,我們初始化了所有屬性的值,包括 'type' 只讀屬性。

display() 方法列印所有屬性的值。

之後,我們建立了 car 類的物件。現在,您可以嘗試更改 car 物件的 'type' 屬性的值,它將丟擲錯誤,因為它時只讀的。

// Defining the class for car
class Car {
    // Properties
    model: string;
    price: number;
    readonly type: string = 'Car';
    // Constructor
    constructor(model: string, price: number, type: string) {
        this.model = model;
        this.price = price;
        this.type = type;
    }
    // Method
    display(): void {
        console.log(`Model: ${this.model}, Price: ${this.price}, Type: ${this.type}`);
    }
}

// Creating object of Car class
let car = new Car('BMW', 1000000, 'Sedan');
car.display();

// Try to change the value of readonly property
// car.type = 'SUV'; // Error: Cannot assign to 'type' because it is a read-only property.

編譯後,它將生成以下 JavaScript 程式碼。

// Defining the class for car
class Car {
    // Constructor
    constructor(model, price, type) {
        this.type = 'Car';
        this.model = model;
        this.price = price;
        this.type = type;
    }
    // Method
    display() {
        console.log(`Model: ${this.model}, Price: ${this.price}, Type: ${this.type}`);
    }
}
// Creating object of Car class
let car = new Car('BMW', 1000000, 'Sedan');
car.display();
// Try to change the value of readonly property
// car.type = 'SUV'; // Error: Cannot assign to 'type' because it is a read-only property.

輸出

上面程式碼示例的輸出如下:

Model: BMW, Price: 1000000, Type: Sedan

帶類型別名的只讀屬性

類型別名用於為物件定義型別。它也可以包含類似於介面的只讀屬性。

示例

在下面的程式碼中,'Point' 是一個包含 'x' 和 'y' 屬性的類型別名,並且兩者都是隻讀的。

之後,我們定義了型別為 'Point' 的 P1 點,並在定義時初始化了 'X' 和 'Y' 屬性的值。

接下來,嘗試更改 'P1' 點的任何屬性的值。它將丟擲錯誤,因為 P1 的兩個屬性都是隻讀的。

//  Readonly Properties with type alias
type Point = {
    readonly x: number;
    readonly y: number;
}

let p1: Point = { x: 10, y: 20 };
// p1.x = 5; // Error

console.log(p1.x, p1.y);

編譯後,它將生成以下 JavaScript 程式碼。

let p1 = { x: 10, y: 20 };
// p1.x = 5; // Error
console.log(p1.x, p1.y);

輸出

輸出如下:

10 20

Const 與只讀屬性

'const' 關鍵字類似於 'readonly' 關鍵字,但有一些細微的差別。

  • 'const' 關鍵字用於宣告常量變數,而 'readonly' 關鍵字用於宣告物件的只讀屬性。
  • 您需要在宣告時為使用 'const' 關鍵字宣告的變數賦值,但對於 'readonly' 屬性,您可以在建立物件時賦值。
  • 'const' 變數的值在聲明後不能更改,而 'readonly' 屬性的值不能在物件或類外部更改。

何時使用 Readonly

  • **資料完整性:**當您希望確保物件的某些屬性在初始賦值後不會更改時。
  • **函數語言程式設計:**它有助於將不變性作為基石的程式設計正規化。
  • **API 合同:**在建立公開給外部使用者的物件時,您需要保證內部狀態不會意外更改。
廣告