Kurs JavaScript i TypeScript · Moduł 6: Podstawy TypeScript
Projekt końcowy: Typowany system zarządzania Parkiem Jurajskim
W tej lekcji4
Gratulacje - dotarłeś do końcowego projektu modułu o podstawach TypeScript! Przez ostatnie lekcje poznałeś potężne narzędzia typowania: od podstawowych typów, przez tablice, krotki i enumy, aż po interfejsy, typy unii i aliasy. Teraz nadszedł czas, aby połączyć tę wiedzę w jeden kompleksowy projekt.
Wyobraź sobie, że zespół programistów Parku Jurajskiego w końcu postanowił przepisać swoje systemy z czystego JavaScriptu na TypeScript. Po zbyt wielu incydentach spowodowanych błędami typów - od źle przekazanych parametrów zasilania, przez pomylone gatunki dinozaurów, po awarie systemu bezpieczeństwa z powodu undefined - zarząd podjął decyzję: "Nigdy więcej!". Twoim zadaniem jest stworzenie fundamentu nowego, w pełni typowanego systemu zarządzania parkiem.
W tym projekcie zbudujesz kompletny system typów i interfejsów dla Parku Jurajskiego, który zapewni bezpieczeństwo typów na każdym poziomie aplikacji.
Cel projektu
Stworzysz typowany system zarządzania Parkiem Jurajskim składający się z czterech obszarów:
- System typów dla dinozaurów - enumy, interfejsy i unie opisujące wszystkie aspekty dinozaurów
- System zarządzania sektorami - interfejsy i typy dla infrastruktury parku
- System bezpieczeństwa - typy zdarzeń, alertów i protokołów
- Centralny system zarządzania - łączenie wszystkich typów w spójny system
Wymagania funkcjonalne
1. System typów dla dinozaurów (Enumy, interfejsy, aliasy)
Pierwszy obszar to precyzyjny model danych opisujący dinozaury w parku. Używamy enumów dla stałych wartości, interfejsów dla struktury obiektów i aliasów typów dla złożonych kombinacji.
// Enumy - stałe wartości w systemie
enum Diet {
Carnivore = "mięsożerca",
Herbivore = "roślinożerca",
Omnivore = "wszystkożerca",
Piscivore = "rybożerca"
}
enum Era {
Triassic = "trias",
Jurassic = "jura",
Cretaceous = "kreda"
}
enum ThreatLevel {
Minimal = 1,
Low = 2,
Moderate = 3,
High = 4,
Extreme = 5
}
enum DinoStatus {
Healthy = "zdrowy",
Sick = "chory",
Sleeping = "śpi",
Feeding = "je",
Agitated = "pobudzony",
Escaped = "uciekł"
}
// Typ aliasowy - gatunek dinozaura
type Species =
| "Tyrannosaurus Rex"
| "Velociraptor"
| "Triceratops"
| "Brachiosaurus"
| "Stegosaurus"
| "Pteranodon"
| "Dilophosaurus"
| "Gallimimus"
| "Parasaurolophus"
| "Ankylosaurus";
// Interfejs - dane medyczne dinozaura
interface DinoHealth {
weight: number; // w kilogramach
height: number; // w metrach
heartRate: number; // uderzenia na minutę
temperature: number; // stopnie Celsjusza
lastFed: Date;
lastCheckup: Date;
conditions: string[]; // lista stanów zdrowotnych
}
// Interfejs - pełny profil dinozaura
interface Dinosaur {
id: string;
name: string;
species: Species; // Typ aliasowy
diet: Diet; // Enum
era: Era; // Enum
threatLevel: ThreatLevel; // Enum
status: DinoStatus; // Enum
health: DinoHealth; // Zagnieżdżony interfejs
sectorId: string;
trackingChipActive: boolean;
dateAdded: Date;
}
// Typ unii - filtr wyszukiwania dinozaurów
type DinoSearchCriteria =
| { by: "species"; value: Species }
| { by: "diet"; value: Diet }
| { by: "threatLevel"; minLevel: ThreatLevel }
| { by: "status"; value: DinoStatus }
| { by: "sector"; sectorId: string };
// Funkcja z typami
function searchDinosaurs(
dinosaurs: Dinosaur[],
criteria: DinoSearchCriteria
): Dinosaur[] {
switch (criteria.by) {
case "species":
return dinosaurs.filter(d => d.species === criteria.value);
case "diet":
return dinosaurs.filter(d => d.diet === criteria.value);
case "threatLevel":
return dinosaurs.filter(d => d.threatLevel >= criteria.minLevel);
case "status":
return dinosaurs.filter(d => d.status === criteria.value);
case "sector":
return dinosaurs.filter(d => d.sectorId === criteria.sectorId);
}
}Zauważ, jak TypeScript wymusza kompletność obsługi w switch - jeśli dodasz nowy wariant do DinoSearchCriteria, kompilator przypomni Ci o obsłużeniu nowego przypadku.
2. System zarządzania sektorami (Interfejsy i typy złożone)
Drugi obszar to model infrastruktury parku - sektory, ogrodzenia, systemy zasilania i monitoring.
// Typ unii - rodzaj ogrodzenia
type FenceType = "electric" | "concrete" | "reinforced" | "moat";
// Interfejs ogrodzenia
interface Fence {
id: string;
type: FenceType;
voltage: number; // 0 dla nie-elektrycznych
integrity: number; // 0-100%
lastMaintenance: Date;
requiresRepair: boolean;
}
// Enum - status sektora
enum SectorStatus {
Operational = "operacyjny",
Maintenance = "konserwacja",
Lockdown = "blokada",
Evacuated = "ewakuowany",
Offline = "offline"
}
// Interfejs - system zasilania
interface PowerSystem {
mainPowerLevel: number; // 0-100%
backupPowerLevel: number; // 0-100%
isBackupActive: boolean;
solarPanelsOnline: number; // liczba aktywnych paneli
generatorStatus: "running" | "standby" | "failed";
}
// Interfejs sektora z zagnieżdżonymi typami
interface Sector {
id: string;
name: string;
status: SectorStatus;
dinosaurs: Dinosaur[];
fences: Fence[];
power: PowerSystem;
capacity: number; // maksymalna liczba dinozaurów
securityLevel: ThreatLevel;
staff: StaffMember[];
}
// Typ aliasowy - rola pracownika
type StaffRole =
| "weterynarz"
| "strażnik"
| "technik"
| "naukowiec"
| "kierownik"
| "przewodnik";
// Interfejs pracownika
interface StaffMember {
id: string;
name: string;
role: StaffRole;
assignedSector: string;
clearanceLevel: ThreatLevel; // Reużycie enuma w innym kontekście
onDuty: boolean;
specializations: string[];
}
// Typ - podsumowanie stanu sektora
type SectorSummary = {
sectorId: string;
sectorName: string;
status: SectorStatus;
dinoCount: number;
avgFenceIntegrity: number;
powerStatus: "stabilne" | "niskie" | "krytyczne";
staffOnDuty: number;
alerts: number;
};
// Funkcja generująca podsumowanie
function getSectorSummary(sector: Sector): SectorSummary {
const avgFence = sector.fences.reduce(
(sum, f) => sum + f.integrity, 0
) / sector.fences.length;
const powerStatus: SectorSummary["powerStatus"] =
sector.power.mainPowerLevel > 60 ? "stabilne" :
sector.power.mainPowerLevel > 30 ? "niskie" : "krytyczne";
return {
sectorId: sector.id,
sectorName: sector.name,
status: sector.status,
dinoCount: sector.dinosaurs.length,
avgFenceIntegrity: Math.round(avgFence),
powerStatus,
staffOnDuty: sector.staff.filter(s => s.onDuty).length,
alerts: 0
};
}Interfejsy budują się hierarchicznie - Sector zawiera tablice Dinosaur[], Fence[] i StaffMember[], tworząc bogaty model danych.
3. System bezpieczeństwa (Typy unii i aliasy)
Trzeci obszar to system zdarzeń i alertów bezpieczeństwa, który intensywnie korzysta z typów unii, aby precyzyjnie modelować różne rodzaje incydentów.
// Typy unii dla zdarzeń bezpieczeństwa - każde zdarzenie ma inną strukturę
type SecurityEvent =
| {
type: "fence_breach";
sectorId: string;
fenceId: string;
dinosaurId: string;
severity: "warning" | "critical";
}
| {
type: "power_outage";
sectorId: string;
affectedSystems: string[];
backupActivated: boolean;
}
| {
type: "dinosaur_escape";
dinosaurId: string;
species: Species;
lastKnownSector: string;
threatLevel: ThreatLevel;
}
| {
type: "sensor_failure";
sectorId: string;
sensorIds: string[];
possibleCause: "damage" | "power" | "sabotage" | "unknown";
}
| {
type: "unauthorized_access";
location: string;
personId: string | null;
timestamp: Date;
};
// Enum - priorytet alertu
enum AlertPriority {
Info = "INFO",
Warning = "UWAGA",
Danger = "ZAGROŻENIE",
Critical = "KRYTYCZNY",
Evacuation = "EWAKUACJA"
}
// Interfejs alertu
interface SecurityAlert {
id: string;
event: SecurityEvent;
priority: AlertPriority;
createdAt: Date;
acknowledgedBy: string | null; // ID pracownika lub null
resolved: boolean;
notes: string[];
}
// Typ - protokół odpowiedzi na zagrożenie
type ResponseProtocol = {
alertId: string;
actions: ProtocolAction[];
estimatedTime: number; // w minutach
requiredClearance: ThreatLevel;
};
// Typ unii - akcja protokołu
type ProtocolAction =
| { action: "lockdown"; sectors: string[] }
| { action: "evacuate"; sectors: string[]; priority: "staff" | "visitors" | "all" }
| { action: "deploy_team"; teamType: StaffRole; targetSector: string }
| { action: "activate_backup"; systems: string[] }
| { action: "track_dinosaur"; dinosaurId: string; useHelicopter: boolean };
// Funkcja obsługi zdarzenia z type narrowing
function handleSecurityEvent(event: SecurityEvent): ResponseProtocol {
const actions: ProtocolAction[] = [];
let estimatedTime = 10;
let requiredClearance = ThreatLevel.Moderate;
switch (event.type) {
case "fence_breach":
actions.push({ action: "lockdown", sectors: [event.sectorId] });
actions.push({ action: "deploy_team", teamType: "technik", targetSector: event.sectorId });
if (event.severity === "critical") {
actions.push({ action: "evacuate", sectors: [event.sectorId], priority: "visitors" });
requiredClearance = ThreatLevel.High;
}
break;
case "dinosaur_escape":
actions.push({ action: "track_dinosaur", dinosaurId: event.dinosaurId, useHelicopter: event.threatLevel >= ThreatLevel.High });
actions.push({ action: "lockdown", sectors: [event.lastKnownSector] });
actions.push({ action: "deploy_team", teamType: "strażnik", targetSector: event.lastKnownSector });
estimatedTime = 60;
requiredClearance = ThreatLevel.Extreme;
break;
case "power_outage":
actions.push({ action: "activate_backup", systems: event.affectedSystems });
actions.push({ action: "deploy_team", teamType: "technik", targetSector: event.sectorId });
if (!event.backupActivated) {
actions.push({ action: "lockdown", sectors: [event.sectorId] });
requiredClearance = ThreatLevel.High;
}
break;
case "sensor_failure":
actions.push({ action: "deploy_team", teamType: "technik", targetSector: event.sectorId });
if (event.possibleCause === "sabotage") {
actions.push({ action: "lockdown", sectors: [event.sectorId] });
requiredClearance = ThreatLevel.Extreme;
}
break;
case "unauthorized_access":
actions.push({ action: "deploy_team", teamType: "strażnik", targetSector: event.location });
break;
}
return {
alertId: `PROTOCOL-${Date.now()}`,
actions,
estimatedTime,
requiredClearance
};
}Type narrowing w switch pozwala TypeScriptowi automatycznie zawęzić typ zdarzenia - w bloku case "fence_breach" TypeScript wie, że event ma pola fenceId i severity.
4. Centralny system zarządzania (Łączenie typów)
Ostatni obszar to centralny system, który łączy wszystkie powyższe typy w spójny interfejs zarządzania całym parkiem.
// Interfejs całego parku
interface JurassicPark {
name: string;
sectors: Sector[];
totalDinosaurs: number;
activeAlerts: SecurityAlert[];
operationalStatus: "open" | "restricted" | "closed" | "emergency";
}
// Typ - raport dzienny
type DailyReport = {
date: string;
parkStatus: JurassicPark["operationalStatus"]; // Reużycie typu z interfejsu
sectorSummaries: SectorSummary[];
incidentCount: number;
resolvedIncidents: number;
dinosaurStats: {
total: number;
byDiet: Record<Diet, number>; // Record z enumem jako kluczem
byStatus: Record<DinoStatus, number>;
escaped: number;
};
staffStats: {
totalOnDuty: number;
byRole: Record<StaffRole, number>; // Record z type alias jako kluczem
};
recommendations: string[];
};
// Funkcja generująca raport
function generateDailyReport(park: JurassicPark): DailyReport {
// Inicjalizacja liczników z enumami
const byDiet: Record<Diet, number> = {
[Diet.Carnivore]: 0,
[Diet.Herbivore]: 0,
[Diet.Omnivore]: 0,
[Diet.Piscivore]: 0
};
const byStatus: Record<DinoStatus, number> = {
[DinoStatus.Healthy]: 0,
[DinoStatus.Sick]: 0,
[DinoStatus.Sleeping]: 0,
[DinoStatus.Feeding]: 0,
[DinoStatus.Agitated]: 0,
[DinoStatus.Escaped]: 0
};
// Zliczanie dinozaurów
const allDinos = park.sectors.flatMap(s => s.dinosaurs);
allDinos.forEach(dino => {
byDiet[dino.diet]++;
byStatus[dino.status]++;
});
// Podsumowania sektorów
const sectorSummaries = park.sectors.map(getSectorSummary);
// Rekomendacje na podstawie danych
const recommendations: string[] = [];
if (byStatus[DinoStatus.Escaped] > 0) {
recommendations.push(`KRYTYCZNE: ${byStatus[DinoStatus.Escaped]} dinozaurów uciekło!`);
}
if (byStatus[DinoStatus.Agitated] > allDinos.length * 0.3) {
recommendations.push("UWAGA: Ponad 30% dinozaurów jest pobudzonych - sprawdzić przyczynę");
}
const lowPowerSectors = sectorSummaries.filter(s => s.powerStatus === "krytyczne");
if (lowPowerSectors.length > 0) {
recommendations.push(
`Krytyczny poziom zasilania w sektorach: ${lowPowerSectors.map(s => s.sectorName).join(", ")}`
);
}
return {
date: new Date().toISOString().split("T")[0],
parkStatus: park.operationalStatus,
sectorSummaries,
incidentCount: park.activeAlerts.length,
resolvedIncidents: park.activeAlerts.filter(a => a.resolved).length,
dinosaurStats: {
total: allDinos.length,
byDiet,
byStatus,
escaped: byStatus[DinoStatus.Escaped]
},
staffStats: {
totalOnDuty: park.sectors.flatMap(s => s.staff).filter(s => s.onDuty).length,
byRole: {
weterynarz: 0, strażnik: 0, technik: 0,
naukowiec: 0, kierownik: 0, przewodnik: 0
}
},
recommendations
};
}Wskazówki implementacyjne
Przy projektowaniu systemu typów pamiętaj o kluczowych zasadach:
Używaj enumów dla stałych zbiorów wartości:
// Dobrze - wartości są stałe i znane z góry
enum Diet { Carnivore = "mięsożerca", Herbivore = "roślinożerca" }
// Źle - zbyt dynamiczne dane dla enuma
enum DinosaurName { Rex = "Rex", Blue = "Blue" } // Imiona mogą być dowolneInterfejsy dla struktur obiektów, aliasy dla unii i kombinacji:
// Interfejs - opisuje kształt obiektu
interface Dinosaur {
name: string;
species: Species;
}
// Alias - łączy typy, tworzy warianty
type SearchResult = Dinosaur | null;
type DinoFilter = (dino: Dinosaur) => boolean;
type DinoOrError = { success: true; data: Dinosaur } | { success: false; error: string };Typy unii dyskryminowane (discriminated unions) dla zdarzeń:
// Pole "type" pozwala TypeScriptowi rozróżniać warianty
type Event =
| { type: "A"; fieldA: string }
| { type: "B"; fieldB: number };
function handle(event: Event) {
if (event.type === "A") {
// TypeScript wie, że tu jest fieldA
console.log(event.fieldA);
}
}Record do tworzenia mapowań z enumów:
// Automatyczna mapa enum → wartość
const dietLabels: Record<Diet, string> = {
[Diet.Carnivore]: "Mięsożerca - karmić mięsem",
[Diet.Herbivore]: "Roślinożerca - karmić roślinami",
[Diet.Omnivore]: "Wszystkożerca - dieta mieszana",
[Diet.Piscivore]: "Rybożerca - karmić rybami"
};Powodzenia!
Ten projekt to Twoja szansa na udowodnienie, że rozumiesz moc systemu typów TypeScript. W prawdziwym Parku Jurajskim każda pomyłka może kosztować życie - a TypeScript to Twoje ogrodzenie chroniące przed błędami typów. Jak powiedział Dr. Alan Grant: "Dinozaury i człowiek - dwa gatunki oddzielone przez 65 milionów lat ewolucji - nagle znów muszą żyć obok siebie." A TypeScript sprawia, że ta koegzystencja jest bezpieczna i przewidywalna.
Stwórz swój typowany system zarządzania w edytorze poniżej. Zdefiniuj przynajmniej trzy enumy, cztery interfejsy, dwa typy unii i jedną funkcję wykorzystującą te typy.
Kod do tej lekcji: index.ts
// Projekt koncowy: Typowany system zarzadzania Parkiem Jurajskim
// Polacz: TypeScript types, interfaces, enums, unie, aliasy
// === 1. ENUMY I STALE ===
// TODO: Zdefiniuj enumy dla systemu parku
enum Diet {
Carnivore = "miesozerca",
Herbivore = "roslinozerca",
Omnivore = "wszystkozerca",
}
enum ThreatLevel {
Minimal = 1,
Low = 2,
Moderate = 3,
High = 4,
Extreme = 5,
}
// TODO: Dodaj enum DinoStatus i Era
// === 2. INTERFEJSY ===
// TODO: Stworz interfejs IDinosaur
interface IDinosaur {
id: string;
name: string;
species: string;
diet: Diet;
weight: number;
threatLevel: ThreatLevel;
// TODO: Dodaj pozostale pola: isHealthy, enclosure, era
}
// TODO: Stworz interfejs IEnclosure
interface IEnclosure {
id: string;
name: string;
// TODO: Dodaj pola: capacity, currentOccupants, securityLevel, isElectrified
}
// === 3. TYPY UNII I ALIASY ===
// TODO: Stworz typ AlertType = "breach" | "health" | "power" | "weather"
// TODO: Stworz typ SecurityEvent z discriminated union
// === 4. FUNKCJE Z TYPAMI ===
// TODO: Stworz typowana funkcje registerDinosaur
function registerDinosaur(data: Omit<IDinosaur, "id">): IDinosaur {
// TODO: Dodaj automatyczne ID i zwroc pelny obiekt
return { id: "DINO-001", ...data };
}
// TODO: Stworz funkcje assignToEnclosure(dino: IDinosaur, enclosure: IEnclosure): boolean
// TODO: Stworz funkcje generateSecurityReport(dinosaurs: IDinosaur[]): string
// === 5. TEST SYSTEMU ===
// TODO: Stworz kilka dinozaurow i przypisz do zagrod
// TODO: Wygeneruj raport bezpieczenstwa
console.log("Typowany system zarzadzania uruchomiony!");Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?