目的
TypeScript の**ジェネリック(Generics)**を使うことで、型を柔軟に受け取り、再利用性の高いクラスを作成することができます。この記事では、人物名のリストを管理する汎用的なクラスを例に、ジェネリックの活用方法を紹介します。
ジェネリックの利点
-
型安全性を保ちながら、複数の型に対応可能。
-
コードの再利用性が高まる。
-
使用時に明示的に型を指定することで、コンパイル時に不正な操作を検出できる。
サンプルコード
class HistoryDataBase<T> {
private _greatPeopleList: T[] = [];
add(item: T) {
this._greatPeopleList.push(item);
}
remove(item: T) {
const index = this._greatPeopleList.indexOf(item);
if (index !== -1) {
this._greatPeopleList.splice(index, 1); // ← slice → splice に修正
} else {
console.log("I'm a self that doesn't exist");
}
}
get() {
return this._greatPeopleList;
}
}
// 文字列型の履歴データベースを作成
const historyDataBase = new HistoryDataBase<string>();
// データを追加
historyDataBase.add("Oda Nobunaga");
historyDataBase.add("Toyotomi Hideyoshi");
historyDataBase.add("Tokugawa Ieyasu");
historyDataBase.add("Saigo Takamori");
historyDataBase.add("Sakamoto Ryoma");
historyDataBase.add("Kukai");
historyDataBase.add("Shotoku Taishi");
historyDataBase.add("Fukuzawa Yukichi");
historyDataBase.add("Nitobe Inazo");
historyDataBase.add("Hideyo Noguchi");
// データを削除
historyDataBase.remove("Kukai");
historyDataBase.remove("Nitobe Inazo");
// 結果を出力
console.log(historyDataBase.get());
解説ポイント
-
class HistoryDataBase<T>
により、任意の型T
を受け取る汎用クラスを定義。 -
add
メソッドで要素を追加、remove
メソッドで存在チェック後に削除。 -
splice(index, 1)
を使うことで、配列から要素を正しく削除可能。 -
呼び出し側では
new HistoryDataBase<string>()
のように型を指定して使用。
応用例
このクラスは、人物名だけでなく、数値やオブジェクトなどさまざまな型で活用可能です。
const numberList = new HistoryDataBase<number>();
numberList.add(100);
numberList.add(200);
console.log(numberList.get()); // [100, 200]
このように、ジェネリックを使うことで柔軟かつ型安全な設計が可能になります。