Kurs JavaScript i TypeScript · Moduł 7: Zaawansowany TypeScript
Klasy generyczne
W tej lekcji9
"Każda zagroda w Parku Jurajskim musi być dostosowana do specyficznego gatunku dinozaura," wyjaśnia Dr. Ellie Sattler, kierowniczka działu badań botanicznych. "Ale mimo różnic, wszystkie zagrody działają według tych samych zasad - kontrola wejść, monitorowanie warunków środowiskowych, zautomatyzowane systemy karmienia. To, co różni zagrodę dla welociraptora od zagrody dla triceratopsa, to nie jej struktura, ale parametry."
Tak samo działają klasy generyczne w TypeScript. Pozwalają na tworzenie wielokrotnie używalnych komponentów, które mogą pracować z różnymi typami danych, przy jednoczesnym zachowaniu pełnej kontroli typów. Jeśli w funkcjach generycznych zobaczyliśmy podstawową ideę generyczności, to klasy generyczne pokazują pełny potencjał tego mechanizmu.
Czym są klasy generyczne?
Klasy generyczne to szablony klas, które mogą działać z różnymi typami danych. Podobnie jak funkcje generyczne, używają one parametrów typu (np. <T>), ale pozwalają na wykorzystanie tych parametrów w całej klasie - w polach, metodach i konstruktorach.
Oto prosta klasa generyczna reprezentująca zagrodę dla dinozaurów:
class DinosaurEnclosure<T> {
private inhabitants: T[];
constructor() {
this.inhabitants = [];
}
addInhabitant(dino: T): void {
this.inhabitants.push(dino);
console.log("Dodano nowego mieszkańca zagrody!");
}
getInhabitants(): T[] {
return [...this.inhabitants]; // Zwracamy kopię, aby uniknąć bezpośredniej modyfikacji
}
countInhabitants(): number {
return this.inhabitants.length;
}
}Powyższa klasa może być użyta do stworzenia zagrody dla dowolnego typu dinozaurów:
// Definicje typów dinozaurów
interface Velociraptor {
name: string;
speed: number;
clawLength: number;
}
interface Triceratops {
name: string;
hornLength: number;
weight: number;
}
// Tworzenie wyspecjalizowanych zagród
const raptorEnclosure = new DinosaurEnclosure<Velociraptor>();
const triceratopsEnclosure = new DinosaurEnclosure<Triceratops>();
// Dodawanie mieszkańców do zagród
raptorEnclosure.addInhabitant({
name: "Blue",
speed: 70,
clawLength: 15
});
triceratopsEnclosure.addInhabitant({
name: "Topsy",
hornLength: 80,
weight: 9000
});
// Sprawdzanie mieszkańców
console.log(`Liczba welociraptorów: ${raptorEnclosure.countInhabitants()}`);
console.log(`Liczba triceratopsów: ${triceratopsEnclosure.countInhabitants()}`);
// TypeScript zapewnia bezpieczeństwo typów
// To nie skompiluje się:
// raptorEnclosure.addInhabitant({
// name: "Invalid",
// hornLength: 50,
// weight: 7000
// });Klasy z wieloma parametrami typów
Klasy generyczne mogą używać wielu parametrów typów, co pozwala na jeszcze większą elastyczność:
class ParkResearchLab<TSpecimen, TResult> {
private specimens: TSpecimen[] = [];
private results: Map<string, TResult> = new Map();
addSpecimen(id: string, specimen: TSpecimen): void {
this.specimens.push(specimen);
console.log(`Dodano próbkę #${id}`);
}
recordResult(specimenId: string, result: TResult): void {
this.results.set(specimenId, result);
console.log(`Zapisano wynik dla próbki #${specimenId}`);
}
getResult(specimenId: string): TResult | undefined {
return this.results.get(specimenId);
}
}
// Przykład użycia z konkretnymi typami
interface BloodSample {
dinosaurId: string;
extractionDate: Date;
volume: number;
}
interface BloodTestResult {
oxygenLevel: number;
whiteBloodCellCount: number;
isHealthy: boolean;
}
const bloodLab = new ParkResearchLab<BloodSample, BloodTestResult>();
bloodLab.addSpecimen("BLD-001", {
dinosaurId: "TREX-01",
extractionDate: new Date(2023, 4, 15),
volume: 250
});
bloodLab.recordResult("BLD-001", {
oxygenLevel: 95,
whiteBloodCellCount: 7500,
isHealthy: true
});
const result = bloodLab.getResult("BLD-001");
console.log(`Wynik badania krwi: ${result?.isHealthy ? "Zdrowy" : "Wymaga uwagi"}`);Rozszerzanie klas generycznych
Klasy generyczne mogą być również rozszerzane, co pozwala na tworzenie bardziej specjalizowanych implementacji:
class MonitoredEnclosure<T> extends DinosaurEnclosure<T> {
private lastCheckTime: Date | null = null;
private securityLevel: "low" | "medium" | "high";
constructor(securityLevel: "low" | "medium" | "high" = "medium") {
super(); // Wywołanie konstruktora klasy bazowej
this.securityLevel = securityLevel;
}
performSecurityCheck(): void {
this.lastCheckTime = new Date();
console.log(`Kontrola bezpieczeństwa wykonana o ${this.lastCheckTime.toLocaleTimeString()}`);
console.log(`Poziom zabezpieczeń: ${this.securityLevel}`);
console.log(`Liczba mieszkańców: ${this.countInhabitants()}`);
}
getLastCheckTime(): Date | null {
return this.lastCheckTime;
}
upgradeSecurityLevel(): void {
if (this.securityLevel === "low") {
this.securityLevel = "medium";
} else if (this.securityLevel === "medium") {
this.securityLevel = "high";
}
console.log(`Zaktualizowano poziom zabezpieczeń do: ${this.securityLevel}`);
}
}
// Użycie rozszerzonej klasy
const monitoredRaptorEnclosure = new MonitoredEnclosure<Velociraptor>("high");
monitoredRaptorEnclosure.addInhabitant({
name: "Delta",
speed: 65,
clawLength: 14
});
monitoredRaptorEnclosure.performSecurityCheck();Parametry typów domyślnych
Podobnie jak funkcje mogą mieć parametry domyślne, klasy generyczne mogą mieć domyślne typy dla swoich parametrów typu:
// Domyślny interfejs dinozaura
interface DefaultDinosaur {
name: string;
species: string;
age: number;
}
// Klasa z domyślnym parametrem typu
class DinosaurTracker<T = DefaultDinosaur> {
private trackedDinos: T[] = [];
trackDinosaur(dino: T, location: string): void {
this.trackedDinos.push(dino);
console.log(`Rozpoczęto śledzenie dinozaura w lokalizacji: ${location}`);
}
getTrackedCount(): number {
return this.trackedDinos.length;
}
}
// Użycie z domyślnym typem
const defaultTracker = new DinosaurTracker();
defaultTracker.trackDinosaur({
name: "Rexy",
species: "Tyrannosaurus Rex",
age: 7
}, "Sektor B");
// Użycie z niestandardowym typem
interface AquaticDinosaur {
name: string;
underwaterSpeedKmh: number;
maxDiveDepthMeters: number;
}
const aquaticTracker = new DinosaurTracker<AquaticDinosaur>();
aquaticTracker.trackDinosaur({
name: "Nessie",
underwaterSpeedKmh: 40,
maxDiveDepthMeters: 500
}, "Jezioro Centralne");Statyczne właściwości w klasach generycznych
Ważne jest, aby zrozumieć, że parametry typu w klasach generycznych odnoszą się tylko do właściwości instancji i metod. Statyczne właściwości i metody są współdzielone między wszystkimi instancjami klasy, niezależnie od ich parametrów typu:
class DinosaurRegistry<T> {
private static totalRegisteredDinos: number = 0;
private registeredDinos: T[] = [];
registerDinosaur(dino: T): void {
this.registeredDinos.push(dino);
DinosaurRegistry.totalRegisteredDinos++;
console.log(`Zarejestrowano nowego dinozaura. Łącznie: ${DinosaurRegistry.totalRegisteredDinos}`);
}
static getTotalRegisteredCount(): number {
return DinosaurRegistry.totalRegisteredDinos;
}
}
const rexRegistry = new DinosaurRegistry<Velociraptor>();
const triRegistry = new DinosaurRegistry<Triceratops>();
rexRegistry.registerDinosaur({
name: "Charlie",
speed: 68,
clawLength: 12
});
triRegistry.registerDinosaur({
name: "Cera",
hornLength: 75,
weight: 8500
});
console.log(`Łączna liczba zarejestrowanych dinozaurów: ${DinosaurRegistry.getTotalRegisteredCount()}`); // 2W tym przykładzie, statyczna zmienna totalRegisteredDinos jest wspólna dla wszystkich instancji DinosaurRegistry, niezależnie od ich parametrów typu.
Klasy generyczne a interfejsy generyczne
Klasy generyczne często współpracują z interfejsami generycznymi, tworząc kompleksowy system typów:
// Interfejs generyczny
interface Repository<T> {
add(item: T): void;
getById(id: string): T | undefined;
getAll(): T[];
update(id: string, item: T): boolean;
delete(id: string): boolean;
}
// Implementacja klasy generycznej zgodnie z interfejsem generycznym
class DinosaurRepository<T extends { id: string }> implements Repository<T> {
private items: Map<string, T> = new Map();
add(item: T): void {
this.items.set(item.id, item);
}
getById(id: string): T | undefined {
return this.items.get(id);
}
getAll(): T[] {
return Array.from(this.items.values());
}
update(id: string, item: T): boolean {
if (this.items.has(id)) {
this.items.set(id, item);
return true;
}
return false;
}
delete(id: string): boolean {
return this.items.delete(id);
}
}
// Użycie repozytorium z konkretnym typem
interface DinosaurRecord {
id: string;
name: string;
species: string;
dateOfBirth: Date;
}
const dinoRepo = new DinosaurRepository<DinosaurRecord>();
dinoRepo.add({
id: "DINO-001",
name: "Rex",
species: "Tyrannosaurus",
dateOfBirth: new Date(2018, 3, 10)
});
const rex = dinoRepo.getById("DINO-001");
console.log(`Znaleziony dinozaur: ${rex?.name}, Gatunek: ${rex?.species}`);Praktyczny przykład: System zarządzania assetami Parku Jurajskiego
Rozbudujmy teraz naszą wiedzę o klasy generyczne, implementując kompleksowy system zarządzania zasobami (assetami) Parku Jurajskiego:
// Podstawowy interfejs dla wszystkich assetów parku
interface ParkAsset {
id: string;
name: string;
status: "operational" | "maintenance" | "offline";
lastUpdated: Date;
}
// Różne typy assetów
interface Vehicle extends ParkAsset {
type: "jeep" | "boat" | "helicopter";
passengerCapacity: number;
currentFuel: number;
}
interface Facility extends ParkAsset {
type: "visitor" | "research" | "security";
location: { x: number, y: number };
capacity: number;
}
interface PowerSystem extends ParkAsset {
type: "main" | "backup" | "sector";
outputCapacity: number;
currentLoad: number;
}
// Generyczny interfejs dla zarządzania assetami
interface AssetManager<T extends ParkAsset> {
registerAsset(asset: T): void;
getAsset(id: string): T | undefined;
updateStatus(id: string, status: T["status"]): boolean;
getOperationalAssets(): T[];
}
// Implementacja generycznej klasy zarządzającej assetami
class JurassicParkAssetManager<T extends ParkAsset> implements AssetManager<T> {
private assets: Map<string, T> = new Map();
private statusChangeLog: { assetId: string, oldStatus: string, newStatus: string, timestamp: Date }[] = [];
constructor(private assetType: string) {
console.log(`Zainicjalizowano system zarządzania assetami typu: ${assetType}`);
}
registerAsset(asset: T): void {
if (this.assets.has(asset.id)) {
throw new Error(`Asset o ID ${asset.id} już istnieje`);
}
this.assets.set(asset.id, {
...asset,
lastUpdated: new Date()
});
console.log(`Zarejestrowano nowy asset: ${asset.name} (ID: ${asset.id})`);
}
getAsset(id: string): T | undefined {
return this.assets.get(id);
}
updateStatus(id: string, status: T["status"]): boolean {
const asset = this.assets.get(id);
if (!asset) {
console.warn(`Nie znaleziono assetu o ID ${id}`);
return false;
}
const oldStatus = asset.status;
// Aktualizacja statusu
const updatedAsset = {
...asset,
status,
lastUpdated: new Date()
};
this.assets.set(id, updatedAsset);
// Logowanie zmiany
this.statusChangeLog.push({
assetId: id,
oldStatus,
newStatus: status,
timestamp: new Date()
});
console.log(`Zaktualizowano status assetu ${asset.name} z "${oldStatus}" na "${status}"`);
return true;
}
getOperationalAssets(): T[] {
return Array.from(this.assets.values())
.filter(asset => asset.status === "operational");
}
getStatusChangeHistory(id?: string): typeof this.statusChangeLog {
if (id) {
return this.statusChangeLog.filter(log => log.assetId === id);
}
return [...this.statusChangeLog];
}
generateReport(): string {
const totalAssets = this.assets.size;
const operational = this.getOperationalAssets().length;
const maintenance = Array.from(this.assets.values())
.filter(asset => asset.status === "maintenance").length;
const offline = Array.from(this.assets.values())
.filter(asset => asset.status === "offline").length;
return `
RAPORT STATUSU ASSETÓW: ${this.assetType.toUpperCase()}
======================================
Łączna liczba: ${totalAssets}
Operacyjne: ${operational} (${Math.round(operational / totalAssets * 100)}%)
W konserwacji: ${maintenance} (${Math.round(maintenance / totalAssets * 100)}%)
Offline: ${offline} (${Math.round(offline / totalAssets * 100)}%)
======================================
Wygenerowano: ${new Date().toLocaleString()}
`;
}
}
// Użycie systemu zarządzania assetami z różnymi typami
const vehicleManager = new JurassicParkAssetManager<Vehicle>("Pojazdy");
const facilityManager = new JurassicParkAssetManager<Facility>("Obiekty");
const powerManager = new JurassicParkAssetManager<PowerSystem>("Zasilanie");
// Rejestracja przykładowych assetów
vehicleManager.registerAsset({
id: "VEH-001",
name: "Explorer 04",
status: "operational",
lastUpdated: new Date(),
type: "jeep",
passengerCapacity: 5,
currentFuel: 75
});
vehicleManager.registerAsset({
id: "VEH-002",
name: "Explorer 05",
status: "maintenance",
lastUpdated: new Date(),
type: "jeep",
passengerCapacity: 5,
currentFuel: 30
});
facilityManager.registerAsset({
id: "FAC-001",
name: "Visitor Center",
status: "operational",
lastUpdated: new Date(),
type: "visitor",
location: { x: 100, y: 200 },
capacity: 200
});
powerManager.registerAsset({
id: "PWR-001",
name: "Main Power Grid",
status: "operational",
lastUpdated: new Date(),
type: "main",
outputCapacity: 10000,
currentLoad: 6500
});
// Symulacja awarii i aktualizacji statusów
vehicleManager.updateStatus("VEH-001", "maintenance");
powerManager.updateStatus("PWR-001", "offline");
facilityManager.updateStatus("FAC-001", "maintenance");
// Po naprawie
setTimeout(() => {
vehicleManager.updateStatus("VEH-001", "operational");
powerManager.updateStatus("PWR-001", "operational");
facilityManager.updateStatus("FAC-001", "operational");
// Generowanie raportów
console.log(vehicleManager.generateReport());
console.log(powerManager.generateReport());
// Historia zmian statusu
console.log("Historia zmian statusu głównego zasilania:");
console.log(powerManager.getStatusChangeHistory("PWR-001"));
}, 3000);Kiedy używać klas generycznych?
Klasy generyczne są szczególnie przydatne w następujących sytuacjach:
- Kolekcje i kontenery danych - gdy potrzebujesz przechowywać i zarządzać elementami różnych typów
- Serwisy i repozytoria - gdy implementujesz wzorce projektowe, które powinny działać z różnymi typami danych
- Komponenty wielokrotnego użytku - gdy chcesz stworzyć elastyczne komponenty, które mogą być używane w różnych kontekstach
- Abstrakcje na różnych poziomach - gdy chcesz zdefiniować hierarchie klas, które mogą być specjalizowane dla różnych typów
Podsumowanie
Klasy generyczne są potężnym narzędziem w TypeScript, które pozwala na tworzenie elastycznego, bezpiecznego pod względem typów kodu. Zapewniają one doskonałą równowagę między reużywalnością a bezpieczeństwem typów, umożliwiając tworzenie komponentów, które:
- Mogą działać z różnymi typami danych
- Zachowują pełne informacje o typach
- Zapewniają wsparcie kompilatora i IDE (podpowiedzi, weryfikacja typów)
- Są czytelne i zrozumiałe dla innych programistów
Podobnie jak w Parku Jurajskim, gdzie infrastruktura musi być elastyczna, aby obsłużyć różne gatunki dinozaurów, klasy generyczne pozwalają nam budować systemy, które są zarówno elastyczne, jak i bezpieczne - idealne połączenie dla nowoczesnego rozwoju oprogramowania.
W następnym ćwiczeniu przyjrzymy się, jak możemy dodatkowo udoskonalić nasze generyki, używając ograniczeń generycznych (constraints), aby zapewnić, że nasze generyczne klasy i funkcje działają tylko z typami, które spełniają określone wymagania.
Kod do tej lekcji: index.ts
// Klasy generyczne - Park Jurajski
console.log("=== KLASY GENERYCZNE ===\n");
// ===========================================
// 1. GenericRepository<T> - repozytorium danych
// ===========================================
interface Identifiable {
id: number;
name: string;
}
class GenericRepository<T extends Identifiable> {
private items: Map<number, T> = new Map();
private label: string;
constructor(label: string) {
this.label = label;
}
add(item: T): void {
this.items.set(item.id, item);
}
getById(id: number): T | undefined {
return this.items.get(id);
}
getAll(): T[] {
return Array.from(this.items.values());
}
remove(id: number): boolean {
return this.items.delete(id);
}
count(): number {
return this.items.size;
}
find(predicate: (item: T) => boolean): T[] {
return this.getAll().filter(predicate);
}
toString(): string {
return `[${this.label}] ${this.count()} rekordow`;
}
}
// ===========================================
// 2. Collection<T> - kolekcja z iteracja
// ===========================================
class Collection<T> {
private elements: T[] = [];
add(...items: T[]): Collection<T> {
this.elements.push(...items);
return this; // Fluent API
}
first(): T | undefined {
return this.elements[0];
}
last(): T | undefined {
return this.elements[this.elements.length - 1];
}
map<U>(fn: (item: T) => U): Collection<U> {
const result = new Collection<U>();
result.add(...this.elements.map(fn));
return result;
}
filter(fn: (item: T) => boolean): Collection<T> {
const result = new Collection<T>();
result.add(...this.elements.filter(fn));
return result;
}
toArray(): T[] {
return [...this.elements];
}
get size(): number {
return this.elements.length;
}
}
// ===========================================
// 3. Pair<A, B> - para wartosci
// ===========================================
class Pair<A, B> {
constructor(
public readonly first: A,
public readonly second: B
) {}
swap(): Pair<B, A> {
return new Pair(this.second, this.first);
}
toString(): string {
return `(${this.first}, ${this.second})`;
}
}
// ===========================================
// Test
// ===========================================
// --- GenericRepository ---
interface Dinosaur {
id: number;
name: string;
species: string;
weight: number;
}
interface Enclosure {
id: number;
name: string;
capacity: number;
}
const dinoRepo = new GenericRepository<Dinosaur>("Dinozaury");
dinoRepo.add({ id: 1, name: "Rexy", species: "T-Rex", weight: 8000 });
dinoRepo.add({ id: 2, name: "Blue", species: "Velociraptor", weight: 15 });
dinoRepo.add({ id: 3, name: "Cera", species: "Triceratops", weight: 6000 });
const encRepo = new GenericRepository<Enclosure>("Zagodzenia");
encRepo.add({ id: 101, name: "Strefa T-Rex", capacity: 2 });
encRepo.add({ id: 102, name: "Dolina Raptorow", capacity: 6 });
console.log(dinoRepo.toString());
console.log(encRepo.toString());
console.log("\nDinozaur #2:", dinoRepo.getById(2)?.name);
console.log("Ciezkie (>1000kg):", dinoRepo.find(d => d.weight > 1000).map(d => d.name).join(", "));
// --- Collection ---
console.log("\n--- Collection z fluent API ---");
const names = new Collection<string>()
.add("Rexy", "Blue", "Delta", "Charlie", "Cera")
.filter(n => n.length <= 4)
.map(n => n.toUpperCase());
console.log("Krotkie nazwy:", names.toArray().join(", "));
console.log("Pierwsza:", names.first());
console.log("Ostatnia:", names.last());
// --- Pair ---
console.log("\n--- Pair ---");
const dinoEnclosure = new Pair<string, string>("Rexy", "Strefa T-Rex");
console.log("Para:", dinoEnclosure.toString());
const swapped = dinoEnclosure.swap();
console.log("Zamieniona:", swapped.toString());
const idWeight = new Pair<number, number>(1, 8000);
console.log("ID-Waga:", idWeight.toString());
console.log("\nKlasy generyczne zapewniaja bezpieczenstwo typow!");Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Kiedy lepiej użyć generyka <T> zamiast union type (string | number)?
Zadania praktyczne w grze
- Edytor kodu
Stwórz generyczne repozytorium danych parku
- Układanie w pionie
Uporządkuj modyfikatory dostępu od najbardziej restrykcyjnego do najszerszego: