TypeScript 中的只讀屬性
在 TypeScript 中,屬性是定義物件結構和行為的重要組成部分。它們允許我們封裝資料並提供訪問和操作資料的方法。預設情況下,TypeScript 中的屬性既可讀又可寫,這意味著它們既可以訪問也可以修改。但是,在某些情況下,我們可能希望建立只能讀取而不能修改的屬性。這就是隻讀屬性發揮作用的地方。
只讀屬性提供了一種定義只能訪問而不能更改其值後修改的屬性的方法。當您希望確保某些資料保持不變並且不會意外修改時,它們特別有用。在本教程中,我們將探討 TypeScript 中的只讀屬性,瞭解它們的工作原理,並檢視其用法的實際示例。
語法
要在 TypeScript 中定義只讀屬性,我們在屬性名前加readonly關鍵字。
封裝實體可以在 TypeScript 中是類或介面。
class MyClass {
readonly propertyName: type;
}
您可以將MyClass替換為您類的名稱,將propertyName替換為只讀屬性所需的名稱,並將type替換為適當的資料型別。
理解只讀屬性
這些只讀屬性只能讀取,永遠不能修改。任何嘗試修改只讀屬性的操作都將導致編譯時錯誤。另外,請注意,TypeScript 中沒有執行時檢查來強制執行此操作,並且生成的 JavaScript 等效程式碼沒有任何方法來驗證只讀屬性。
在下面的示例中,Person 類的 name 和 age 屬性被標記為只讀。一旦這些屬性被分配了一個值,它們的値就不能更改,任何嘗試都將導致 linting 和編譯時錯誤。
class Person {
readonly name: string;
readonly age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
只讀屬性的用法和益處
只讀屬性在 TypeScript 開發中提供了許多好處和用例。讓我們探索其中的一些 -
示例 1:不可變物件
只讀屬性可用於建立不可變物件。不可變物件是在建立後其狀態無法更改的物件。透過將所有屬性標記為只讀,我們確保物件的狀態在其整個生命週期中保持不變。這在您希望保證某些資料保持不變的場景中特別有用,可以防止可能引入錯誤或意外行為的意外修改。
class Circle {
readonly radius: number;
readonly area: number;
constructor(radius: number) {
this.radius = radius;
this.area = Math.PI * radius * radius;
}
}
const circle = new Circle(5);
console.log(`The area of the circle is: ${circle.area}`); // Output: 78.53981633974483
// circle.area = 100;
編譯後,它將生成以下 JavaScript 程式碼 -
var Circle = /** @class */ (function () {
function Circle(radius) {
this.radius = radius;
this.area = Math.PI * radius * radius;
}
return Circle;
}());
var circle = new Circle(5);
console.log("The area of the circle is: ".concat(circle.area)); // Output: 78.53981633974483
// circle.area = 100;
輸出
以上程式碼將產生以下輸出 -
The area of the circle is: 78.53981633974483
在上面的示例中,Circle 類的 radius 和 area 屬性被標記為只讀。一旦建立了 Circle 物件,其屬性就不能修改,從而確保計算出的 area 保持不變,並且與 radius 值一致。
最後一行嘗試修改circle物件的只讀屬性area,因此會導致錯誤。您可以透過取消註釋上面一行程式碼來檢查它。
Error: Cannot assign to 'area' because it is a read-only property.
示例 2:安全重構
在重構程式碼時,只讀屬性也起著重要作用。當您將屬性標記為只讀時,TypeScript 編譯器可以幫助您識別並防止意外修改該屬性。如果您嘗試修改只讀屬性,編譯器將引發錯誤,從而更容易在開發過程中捕獲和修復潛在的錯誤。
class Car {
readonly brand: string;
readonly model: string;
constructor(brand: string, model: string) {
this.brand = brand;
this.model = model;
}
}
const car = new Car("Toyota", "Corolla");
console.log(`The brand of the car is: ${car.brand}`); // Output: "Toyota"
// car.brand = "Honda"; // Error: Cannot assign to 'brand' because it is a read-only property
編譯後,它將生成以下 JavaScript 程式碼 -
var Car = /** @class */ (function () {
function Car(brand, model) {
this.brand = brand;
this.model = model;
}
return Car;
}());
var car = new Car("Toyota", "Corolla");
console.log("The brand of the car is: ".concat(car.brand)); // Output: "Toyota"
// car.brand = "Honda"; // Error: Cannot assign to 'brand' because it is a read-only property
輸出
以上程式碼將產生以下輸出 -
The brand of the car is: Toyota
在上面的示例中,Car 類的 brand 和 model 屬性被標記為只讀。如果我們嘗試為 brand 屬性分配新值,TypeScript 編譯器將引發錯誤,從而防止意外修改。
示例 3:增強的可讀性和意圖
透過使用只讀屬性,我們可以更明確地傳達某些屬性的預期行為和用法。當您在類或介面中遇到只讀屬性時,很明顯它的值不應被修改。這提高了程式碼的可讀性,並使其他開發人員更容易理解程式碼庫並遵循最佳實踐。
interface Point {
readonly x: number;
readonly y: number;
}
function calculateDistance(point1: Point, point2: Point): number {
const dx = point2.x - point1.x;
const dy = point2.y - point1.y;
return Math.sqrt(dx * dx + dy * dy);
}
const point1: Point = { x: 0, y: 0 };
const point2: Point = { x: 3, y: 4 };
// point1.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.
console.log(
`The distance between the points is: ${calculateDistance(point1, point2)}`
); // Output: 5
編譯後,它將生成以下 JavaScript 程式碼 -
function calculateDistance(point1, point2) {
var dx = point2.x - point1.x;
var dy = point2.y - point1.y;
return Math.sqrt(dx * dx + dy * dy);
}
var point1 = { x: 0, y: 0 };
var point2 = { x: 3, y: 4 };
// point1.x = 5; // Error: Cannot assign to 'x' because it is a read-only property.
console.log("The distance between the points is: ".concat(calculateDistance(point1, point2))); // Output: 5
輸出
以上程式碼將產生以下輸出 -
The distance between the points is: 5
在上面的示例中,Point 介面的 x 和 y 屬性被標記為只讀。這清楚地傳達了在計算距離期間,點的座標不應更改。
結論
TypeScript 中的只讀屬性允許我們定義只能讀取而不能修改的屬性。使用 readonly 關鍵字修飾符可以強制執行不變性和防止意外修改某些資料。只讀屬性提供了許多好處,包括建立不可變物件、更安全的重構和改進的程式碼可讀性。它們在維護程式碼完整性、在開發過程中捕獲潛在錯誤以及傳達屬性的預期行為方面發揮著至關重要的作用。
在設計 TypeScript 類和介面時,請考慮在適當的地方使用只讀屬性,以確保資料一致性並減少因意外修改而引入意外行為的可能性。透過有效地利用只讀屬性,您可以建立更健壯和可靠的 TypeScript 程式碼庫。
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP