如何在 TypeScript 中使物件屬性不可變?
不可變物件屬性的簡單定義是我們一旦定義並初始化物件屬性後無法修改的屬性。
我們可以使用 const 關鍵字,但必須在建立屬性時初始化該屬性。因此,我們必須使用 readonly 關鍵字來使屬性不可變,允許它只讀。因此,一旦我們初始化了屬性,我們就無法修改屬性的值。
語法
使用者可以按照以下語法使用 readonly 關鍵字使物件屬性不可變。
interface test { readonly property1: boolean; } var object: test = { property1: false, };
在以上語法中,‘test’ 介面的 property1 是不可變的,因為它只是只讀的,我們無法在物件塊外部更改其狀態。
示例
在下面的示例中,immutableObject 包含 key1、key2 和 key3。我們已將 readonly 關鍵字與 key1 和 key2 一起使用以使這些屬性不可變。
我們已在類建構函式中初始化了不可變屬性。如果我們不在類建構函式中初始化不可變物件屬性,則會生成編譯錯誤。
此外,我們無法在類外部更改不可變物件屬性的值。
class immutableObject { readonly key1: boolean; readonly key2: string; key3: number; constructor(value1: boolean, value2: string, value3: number) { this.key1 = value1; this.key2 = value2; this.key3 = value3; } } let obj = new immutableObject(true, "hello",5450); console.log("The object properties are "); console.log(obj.key1) console.log(obj.key2) console.log(obj.key3) // obj.key1 = false; // modifying the key1 is not allowed as it is immutable
編譯後,它將生成以下 JavaScript 程式碼:
var immutableObject = /** @class */ (function () { function immutableObject(value1, value2, value3){ this.key1 = value1; this.key2 = value2; this.key3 = value3; } return immutableObject; }()); var obj = new immutableObject(true, "hello", 5450); console.log("The object properties are "); console.log(obj.key1); console.log(obj.key2); console.log(obj.key3); // obj.key1 = false; // modifying the key1 is not allowed as it is immutable
輸出
以上程式碼將產生以下輸出:
The object properties are true hello 5450
示例
在此示例中,我們建立了陣列。陣列的型別為ReadonlyArray。使用者可以嘗試更改陣列中任何索引處的值,並且他們會收到編譯錯誤,因為我們無法更改不可變屬性的值。
此外,使用者可以嘗試使用陣列的push() 和pop() 方法更新不可變陣列,並在輸出中觀察編譯錯誤。
let array: ReadonlyArray<number> = [10, 64, 43, 34]; console.log("The value at 1st index is " + array[1]); // We can't perform push, and pop() operation on the array as it is readonly // array.push(30); // array.pop();
編譯後,它將生成以下 JavaScript 程式碼:
var array = [10, 64, 43, 34]; console.log("The value at 1st index is " + array[1]); // We can't perform push, and pop() operation on the array as it is readonly // array.push(30); // array.pop();
輸出
以上程式碼將產生以下輸出:
The value at 1st index is 64
示例
在 TypeScript 中,集合是物件。在此示例中,我們建立了集合物件,其型別為 ReadonlySet,這使得集合不可變。使用者可以看到,我們可以透過迭代集合來訪問集合的每個元素,但我們無法向集合中新增或從中刪除元素。
let newSet: ReadonlySet<string> = new Set([ "Hi!", "Hi!", "Hello", "TypeScript", "JavaScript", ]); console.log("The elements of set are "); newSet.forEach((ele) => { console.log(ele); }); // adding to the newest is not allowed as it is an immutable object // newSet.add("string")
編譯後,它將生成以下 JavaScript 程式碼:
var newSet = new Set([ "Hi!", "Hi!", "Hello", "TypeScript", "JavaScript", ]); console.log("The elements of set are "); newSet.forEach(function (ele) { console.log(ele); }); // adding to the newest is not allowed as it is an immutable object // newSet.add("string")
輸出
以上程式碼將產生以下輸出:
The elements of set are Hi! Hello TypeScript JavaScript
在本教程中,使用者學習瞭如何使用 readonly 關鍵字建立不可變物件。此外,他們還學習瞭如何建立不可變的集合和陣列。
使用不可變物件的好處在於它提供了程式碼的安全性和提高了程式碼的效能。