如何開發泛型類


在開發實際的泛型類之前,讓我們首先了解泛型類。泛型TypeScript類可以處理多種型別的資料。它是一種多引數型別,使用尖括號 (<>) 表示。這表示類將使用哪種型別的資料來實現這一點。然後可以在類的屬性和函式中使用型別引數,使類更靈活,並可與其他資料型別重複使用。

我們將簡要介紹一下。假設在一個例子中,型別引數表示為“T”,簡單泛型類“MyGenericClass”的屬性“value”。可以同時建立“T”和“value”。如果用不同的型別(例如“number”或“string”)例項化此類,“value”屬性將具有相應的型別。

由於同一個類可以與多種資料型別一起使用,這使得您的程式碼更靈活,可重用性更高。您還可以使用約束來限制用作型別引數的型別。

語法

在 TypeScript 中建立泛型類的語法如下:

class ClassName<TypeParameter> {
   // class properties and methods
}

其中“ClassName”是類的名稱,“TypeParameter”是類將使用的型別資料的佔位符。

示例 1

此示例演示如何在 TypeScript 中使用泛型類來建立一個可以處理多種資料型別的類。該類用型別引數 T 定義,該引數用於類的屬性和方法中,允許該類靈活地與不同型別的資料重複使用。“Queue”類具有一個名為“data”的私有屬性,這是一個 T 型別的陣列。

該類還具有三個方法:“enqueue”,它將一個專案新增到佇列的末尾;“dequeue”,它從佇列的前面移除一個專案;以及“peek”,它返回佇列前面端的專案而不將其移除。我們建立了 Queue 類的兩個例項,一個用於數字,另一個用於字串。該類可以處理不同型別的資料,使我們的程式碼更靈活,可重用性更高。

class Queue<T> {
   private data: T[] = []

   // add an item to the end of the queue
   enqueue(item: T) {
      this.data.push(item)
   }

   // remove an item from the front of the queue
   dequeue(): T | undefined {
      return this.data.shift()
   }

   // get the item at the front of the queue
   peek(): T | undefined {
      return this.data[0]
   }
}
let numberQueue = new Queue<number>()
numberQueue.enqueue(1)
numberQueue.enqueue(2)
console.log(numberQueue.peek())
console.log(numberQueue.dequeue())
console.log(numberQueue.peek())

let stringQueue = new Queue<string>()
stringQueue.enqueue('Hello')
stringQueue.enqueue('world')
console.log(stringQueue.peek())
console.log(stringQueue.dequeue())
console.log(stringQueue.peek())

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

var Queue = /** @class */ (function () {
   function Queue() {
      this.data = [];
   }
   // add an item to the end of the queue
   Queue.prototype.enqueue = function (item) {
      this.data.push(item);
   };
   // remove an item from the front of the queue
   Queue.prototype.dequeue = function () {
      return this.data.shift();
   };
   // get the item at the front of the queue
   Queue.prototype.peek = function () {
      return this.data[0];
   };
   return Queue;
}());
var numberQueue = new Queue();
numberQueue.enqueue(1);
numberQueue.enqueue(2);
console.log(numberQueue.peek());
console.log(numberQueue.dequeue());
console.log(numberQueue.peek());
var stringQueue = new Queue();
stringQueue.enqueue('Hello');
stringQueue.enqueue('world');
console.log(stringQueue.peek());
console.log(stringQueue.dequeue());
console.log(stringQueue.peek());

輸出

以上程式碼將產生以下輸出:

1
1
2
Hello
Hello
world

示例 2

在這個例子中,我們將開發另一個具有兩種泛型型別屬性的泛型類。“KeyValuePair”類有兩個私有屬性,“key”和“value”,分別為 T 和 U 型別。該類還有兩個方法,“getKey”和“getValue”,分別返回鍵和值屬性。

該類可以用數字、字串或物件等資料型別來例項化鍵和值。我們建立了 KeyValuePair 類的兩個例項,一個使用字串作為鍵,數字作為值,另一個使用字串作為鍵,物件作為值。該類可以處理鍵和值的不同資料型別,使我們的程式碼更靈活,可重用性更高。

class KeyValuePair<T, U> {
   private key: T
   private value: U

   constructor(key: T, value: U) {
      this.key = key
      this.value = value
   }

   // method to get the key
   getKey(): T {
      return this.key
   }

   // method to get the value
   getValue(): U {
      return this.value
   }
}

let numberKeyValuePair = new KeyValuePair<string, number>('age', 20)
console.log(numberKeyValuePair.getKey()) // "age"
console.log(numberKeyValuePair.getValue()) // 20

let objectKeyValuePair = new KeyValuePair<string, object>('person', {
   name: 'Tutorialspoint',
   age: 10,
})
console.log(objectKeyValuePair.getKey()) // "person"
console.log(objectKeyValuePair.getValue()) // {name: "Tutorialspoint", age: 10}

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

var KeyValuePair = /** @class */ (function () {
   function KeyValuePair(key, value) {
      this.key = key;
      this.value = value;
   }
   // method to get the key
   KeyValuePair.prototype.getKey = function () {
      return this.key;
   };
   // method to get the value
   KeyValuePair.prototype.getValue = function () {
      return this.value;
   };
   return KeyValuePair;
}());
var numberKeyValuePair = new KeyValuePair('age', 20);
console.log(numberKeyValuePair.getKey()); // "age"
console.log(numberKeyValuePair.getValue()); // 20
var objectKeyValuePair = new KeyValuePair('person', {
   name: 'Tutorialspoint',
   age: 10
});
console.log(objectKeyValuePair.getKey()); // "person"
console.log(objectKeyValuePair.getValue()); // {name: "Tutorialspoint", age: 10}

輸出

以上程式碼將產生以下輸出:

age
20
person
{ name: 'Tutorialspoint', age: 10 }

在 TypeScript 中使用泛型類可以使程式碼更靈活、更可重用和更易於維護。此外,TypeScript 的型別檢查系統確保在編譯時正確使用泛型類中使用的型別,進一步提高了程式碼的整體質量和安全性。泛型類是 TypeScript 的一個強大功能,可以用來編寫更可靠、更可重用的程式碼。

更新於:2023年2月21日

141 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告