Kurs JavaScript i TypeScript · Moduł 7: Zaawansowany TypeScript
Conditional types (Typy warunkowe)
W tej lekcji8
"Dr. Wu, mamy taką sytuację," mówi zdenerwowany asystent laboratorium. "Wzór DNA, który próbujemy sekwencjonować, może być albo z gatunku drapieżnych, albo roślinożernych dinozaurów, ale potrzebujemy różnych protokołów przetwarzania zależnie od tego, z którym mamy do czynienia."
Dr. Henry Wu, główny genetyk Parku Jurajskiego, odpowiada spokojnie: "To nie problem. Nasze algorytmy sekwencjonowania są wystarczająco inteligentne, by wykryć markery drapieżnictwa w DNA i automatycznie zastosować odpowiedni protokół. To właśnie elastyczność naszego systemu."
Podobnie jak zaawansowane algorytmy sekwencjonowania DNA w Parku Jurajskim, TypeScript posiada mechanizm zwany typami warunkowymi (conditional types), który pozwala na dynamiczne określanie typów w zależności od innych typów. To narzędzie pozwala na tworzenie bardziej elastycznych i precyzyjnych interfejsów API, które dostosowują się do różnych scenariuszy.
Podstawy typów warunkowych
Typy warunkowe w TypeScript działają podobnie do wyrażeń warunkowych w JavaScript, ale na poziomie typów. Ich składnia przypomina operator trójskładnikowy:
T extends U ? X : YTen zapis należy czytać jako: "Jeśli typ T rozszerza (jest zgodny z) typem U, to wynikiem jest typ X, w przeciwnym razie typ Y".
Prosty przykład
Stwórzmy prostą funkcję, która przetwarza obiekt reprezentujący dinozaura i zwraca różne wyniki w zależności od jego diety:
type Carnivore = { type: "carnivore"; huntingSkill: number };
type Herbivore = { type: "herbivore"; foragingSkill: number };
type Dinosaur = Carnivore | Herbivore;
// Typ warunkowy determinujący odpowiedni typ wyniku
type DinosaurActivity<T extends Dinosaur> = T extends Carnivore
? { activity: "hunting"; preyTargeted: string }
: { activity: "grazing"; plantsConsumed: number };
// Funkcja używająca typu warunkowego
function trackDinosaurActivity<T extends Dinosaur>(dino: T): DinosaurActivity<T> {
if (dino.type === "carnivore") {
// TypeScript wie, że dla Carnivore powinniśmy zwrócić { activity: "hunting"; preyTargeted: string }
return {
activity: "hunting",
preyTargeted: "Gallimimus"
} as DinosaurActivity<T>;
} else {
// TypeScript wie, że dla Herbivore powinniśmy zwrócić { activity: "grazing"; plantsConsumed: number }
return {
activity: "grazing",
plantsConsumed: 42
} as DinosaurActivity<T>;
}
}
// Przykładowe użycie
const trex: Carnivore = { type: "carnivore", huntingSkill: 10 };
const triceratops: Herbivore = { type: "herbivore", foragingSkill: 8 };
const trexActivity = trackDinosaurActivity(trex);
console.log(trexActivity.activity); // "hunting"
console.log(trexActivity.preyTargeted); // "Gallimimus"
const triceratopsActivity = trackDinosaurActivity(triceratops);
console.log(triceratopsActivity.activity); // "grazing"
console.log(triceratopsActivity.plantsConsumed); // 42W tym przykładzie typ DinosaurActivity<T> zmienia się w zależności od tego, czy T rozszerza Carnivore czy nie. Dzięki temu możemy zwracać różne struktury danych, a TypeScript zapewnia pełne wsparcie typów dla obu przypadków.
Dystrybutywne typy warunkowe
Jedną z kluczowych cech typów warunkowych jest ich zachowanie dystrybutywne w przypadku unii typów. Kiedy stosujemy typ warunkowy do unii typów, warunek jest stosowany do każdego elementu unii oddzielnie.
type ToArray<T> = T extends any ? T[] : never;
// Z typem prostym wynik jest prosty
type NumberArray = ToArray<number>; // number[]
// Z unią typów, warunek jest stosowany dystrybutywnie
type NumberOrStringArray = ToArray<number | string>; // number[] | string[]W drugim przypadku, ToArray<number | string> jest równoważne ToArray<number> | ToArray<string>, co daje number[] | string[], a nie (number | string)[].
Możemy zastosować to do naszego przykładu z dinozaurami:
// Definiujemy więcej typów dinozaurów
type TRex = { species: "tyrannosaurus"; strength: number };
type Velociraptor = { species: "velociraptor"; speed: number };
type Triceratops = { species: "triceratops"; armorLevel: number };
type Brachiosaurus = { species: "brachiosaurus"; height: number };
// Typ warunkowy filtrujący drapieżniki
type IsPredator<T> = T extends { species: "tyrannosaurus" | "velociraptor" } ? T : never;
// Zastosowanie dystrybutywne na unii typów
type Predators = IsPredator<TRex | Velociraptor | Triceratops | Brachiosaurus>;
// Wynik: TRex | Velociraptor
// Możemy też wyfiltrować roślinożerców
type IsHerbivore<T> = T extends { species: "triceratops" | "brachiosaurus" } ? T : never;
type Herbivores = IsHerbivore<TRex | Velociraptor | Triceratops | Brachiosaurus>;
// Wynik: Triceratops | BrachiosaurusInferred Types (Wnioskowanie typów)
TypeScript pozwala na wydobywanie (inferencję) typów z innych typów przy użyciu słowa kluczowego infer. Jest to szczególnie przydatne w typach warunkowych.
// Typ, który wydobywa typ zwracany przez funkcję
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
// Przykład użycia
function studyDinosaur(specimen: string): { species: string; age: number } {
return {
species: "Velociraptor",
age: 5
};
}
// Wyodrębniony typ zwracany przez funkcję studyDinosaur
type StudyResult = ReturnType<typeof studyDinosaur>; // { species: string; age: number }W tym przykładzie infer R mówi TypeScriptowi, aby "wydedukował" typ zwracany przez funkcję i przypisał go do typu R, który jest następnie używany jako wynik typu warunkowego.
Możemy stworzyć bardziej skomplikowane przykłady wydobywania typów, na przykład:
// Typ reprezentujący DNA dinozaura
type DinosaurDNA = {
species: string;
genomeSequence: string;
markers: {
predatory?: boolean;
aquatic?: boolean;
flying?: boolean;
size: "small" | "medium" | "large";
};
};
// Wyciągamy markery z DNA
type ExtractMarkers<T> = T extends { markers: infer M } ? M : never;
// Wyciągamy wielkość z markerów
type ExtractSize<T> = T extends { size: infer S } ? S : never;
// Przykładowe użycie
type DinosaurMarkers = ExtractMarkers<DinosaurDNA>;
// { predatory?: boolean; aquatic?: boolean; flying?: boolean; size: "small" | "medium" | "large"; }
type DinosaurSize = ExtractSize<DinosaurMarkers>;
// "small" | "medium" | "large"Praktyczne zastosowania typów warunkowych
Typy warunkowe są szczególnie przydatne w zaawansowanych scenariuszach programowania, takich jak:
1. Tworzenie elastycznych komponentów API
// Przykład API do operacji na dinozaurach
interface DinosaurOperations<T> {
create: (data: T) => Promise<T>;
update: (id: string, data: Partial<T>) => Promise<T>;
delete: (id: string) => Promise<void>;
// Metoda, która zwraca różne typy zależnie od parametru T
analyze: T extends { genomeSequence: string }
? (id: string) => Promise<{ compatibilityScore: number }>
: (id: string) => Promise<{ behaviorPrediction: string }>;
}
// Implementacja dla dinozaurów z sekwencją genomu
interface GenomeSequencedDino {
id: string;
name: string;
genomeSequence: string;
}
// Implementacja dla dinozaurów bez sekwencji genomu
interface BehaviorStudiedDino {
id: string;
name: string;
observedBehaviors: string[];
}
// Różne implementacje dla różnych typów
function createDinosaurAPI<T extends GenomeSequencedDino | BehaviorStudiedDino>(
baseUrl: string
): DinosaurOperations<T> {
return {
create: (data: T) => fetch(`${baseUrl}/create`, {
method: 'POST',
body: JSON.stringify(data)
}).then(res => res.json()),
update: (id: string, data: Partial<T>) => fetch(`${baseUrl}/${id}`, {
method: 'PUT',
body: JSON.stringify(data)
}).then(res => res.json()),
delete: (id: string) => fetch(`${baseUrl}/${id}`, {
method: 'DELETE'
}).then(() => undefined),
// Implementacja metody analyze będzie się różnić w zależności od typu T
analyze: ((id: string) => {
if ('genomeSequence' in { ...({} as T) }) {
return fetch(`${baseUrl}/${id}/genome-analysis`)
.then(res => res.json());
} else {
return fetch(`${baseUrl}/${id}/behavior-analysis`)
.then(res => res.json());
}
}) as any // Potrzebny cast ze względu na ograniczenia TypeScript w czasie wykonania
};
}
// Użycie różnych API
const genomeAPI = createDinosaurAPI<GenomeSequencedDino>('/api/genome-dinos');
const result1 = await genomeAPI.analyze('dino-1'); // { compatibilityScore: number }
const behaviorAPI = createDinosaurAPI<BehaviorStudiedDino>('/api/behavior-dinos');
const result2 = await behaviorAPI.analyze('dino-2'); // { behaviorPrediction: string }2. Implementacja wzorców typu
// Pomocniczy typ Exclude - wyklucza typy z unii
type Exclude<T, U> = T extends U ? never : T;
// Przykład: wykluczanie niebezpiecznych dinozaurów
type DangerousDinosaurs = "Tyrannosaurus" | "Velociraptor" | "Spinosaurus";
type AllDinosaurs = "Tyrannosaurus" | "Triceratops" | "Velociraptor" | "Brachiosaurus" | "Stegosaurus" | "Spinosaurus";
type SafeDinosaurs = Exclude<AllDinosaurs, DangerousDinosaurs>;
// "Triceratops" | "Brachiosaurus" | "Stegosaurus"
// Pomocniczy typ Extract - wyciąga typy spełniające warunek
type Extract<T, U> = T extends U ? T : never;
// Przykład: wyodrębnianie dinozaurów z epoki jurajskiej
type JurassicDinosaurs = "Stegosaurus" | "Brachiosaurus" | "Allosaurus";
type CretaceousDinosaurs = "Tyrannosaurus" | "Triceratops" | "Velociraptor";
type AllEras = JurassicDinosaurs | CretaceousDinosaurs;
type OnlyJurassic = Extract<AllEras, JurassicDinosaurs>;
// "Stegosaurus" | "Brachiosaurus" | "Allosaurus"
// Pomocniczy typ NonNullable - usuwa null i undefined z typu
type NonNullable<T> = T extends null | undefined ? never : T;
// Przykład: upewniamy się, że mamy niepuste dane o dinozaurach
type PossibleDinoData = { name: string; weight: number } | null | undefined;
type DefiniteDinoData = NonNullable<PossibleDinoData>;
// { name: string; weight: number }3. Tworzenie mapperów typów
// Typ Mapper przekształcający właściwości obiektu z jednego typu na inny
type MapProperties<T, U> = {
[K in keyof T]: T[K] extends object ? MapProperties<T[K], U> : U;
};
// Przykład: mapowanie wartości liczbowych na stringi
type DinosaurStats = {
name: string;
physicalTraits: {
height: number;
weight: number;
speed: number;
};
behavioralTraits: {
aggression: number;
intelligence: number;
packBehavior: number;
};
};
// Przekształcamy wszystkie liczby na stringi dla celów wyświetlania
type DinosaurStatsForDisplay = MapProperties<DinosaurStats, string>;
/*
{
name: string;
physicalTraits: {
height: string;
weight: string;
speed: string;
};
behavioralTraits: {
aggression: string;
intelligence: string;
packBehavior: string;
};
}
*/Zaawansowany przykład: System typów dla infrastruktury Parku Jurajskiego
Przyjrzyjmy się bardziej złożonemu przykładowi, który wykorzystuje typy warunkowe do modelowania różnych systemów w Parku Jurajskim:
// --- Podstawowe typy systemów ---
type SystemStatus = "online" | "offline" | "maintenance" | "error";
interface BaseSystem {
id: string;
name: string;
status: SystemStatus;
lastUpdated: Date;
}
// Różne typy systemów w parku
interface SecuritySystem extends BaseSystem {
type: "security";
enclosures: string[];
alertLevel: "low" | "medium" | "high" | "critical";
cameras: number;
motionSensors: number;
}
interface PowerSystem extends BaseSystem {
type: "power";
outputCapacity: number; // kW
currentLoad: number; // kW
backupCapacity: number; // kW
generators: number;
}
interface TransportSystem extends BaseSystem {
type: "transport";
vehicles: number;
routes: string[];
passengerCapacity: number;
automatedGuidance: boolean;
}
interface LifeSupportSystem extends BaseSystem {
type: "lifesupport";
habitats: string[];
environmentalControls: {
temperature: number; // °C
humidity: number; // %
oxygen: number; // %
};
}
// Unia wszystkich typów systemów
type ParkSystem = SecuritySystem | PowerSystem | TransportSystem | LifeSupportSystem;
// --- Typy warunkowe dla danych monitorowania ---
/**
* Typ warunkowy, który określa, jakie dane monitoringu są istotne dla każdego typu systemu
*/
type MonitoringData<T extends ParkSystem> = T extends SecuritySystem
? {
breachDetections: number;
securityFootage: { cameraId: string; timestamp: Date; events: string[] }[];
activeAlarms: string[];
}
: T extends PowerSystem
? {
loadDistribution: { sector: string; load: number }[];
energyEfficiency: number; // %
estimatedBackupTime: number; // hours
powerFluctuations: boolean;
}
: T extends TransportSystem
? {
activeVehicles: number;
passengerCount: number;
delayReports: { routeId: string; delay: number }[];
fuelConsumption: number; // liters/hour
}
: T extends LifeSupportSystem
? {
habitatConditions: {
habitatId: string;
temperature: number;
humidity: number;
oxygenLevel: number;
co2Level: number;
}[];
anomalyDetections: string[];
resourceConsumption: { water: number; electricity: number; air: number };
}
: never; // Fallback dla nieznanych typów
/**
* Typ warunkowy określający zalecane działania dla systemów w różnych stanach
*/
type RecommendedActions<T extends ParkSystem> =
T extends { status: "error" }
? { severity: "high"; actions: string[]; escalation: string; timeToResolve: number }
: T extends { status: "maintenance" }
? { checklistItems: string[]; estimatedCompletionTime: Date; personnelAssigned: string[] }
: T extends { status: "offline" }
? { restartProcedures: string[]; systemDependencies: string[]; estimatedDowntime: number }
: { routineChecks: string[]; nextMaintenanceDate: Date };
// --- Klasa monitorująca systemy wykorzystująca typy warunkowe ---
/**
* Klasa zarządzająca monitoringiem systemów, używająca typów warunkowych
* do zapewnienia typowej poprawności dla różnych systemów
*/
class SystemMonitor<T extends ParkSystem> {
private system: T;
private monitoringData: MonitoringData<T>;
private recommendedActions: RecommendedActions<T>;
constructor(system: T) {
this.system = system;
// Inicjalizacja monitoringData na podstawie typu systemu
this.monitoringData = this.initializeMonitoringData();
// Inicjalizacja recommendedActions na podstawie typu i statusu systemu
this.recommendedActions = this.initializeRecommendedActions();
}
// Metoda pomocnicza do inicjalizacji danych monitorowania
private initializeMonitoringData(): MonitoringData<T> {
// Implementacja zależna od typu T
if (this.system.type === "security") {
return {
breachDetections: 0,
securityFootage: [],
activeAlarms: []
} as MonitoringData<T>;
} else if (this.system.type === "power") {
return {
loadDistribution: [],
energyEfficiency: 95,
estimatedBackupTime: 48,
powerFluctuations: false
} as MonitoringData<T>;
} else if (this.system.type === "transport") {
return {
activeVehicles: 0,
passengerCount: 0,
delayReports: [],
fuelConsumption: 0
} as MonitoringData<T>;
} else if (this.system.type === "lifesupport") {
return {
habitatConditions: [],
anomalyDetections: [],
resourceConsumption: { water: 0, electricity: 0, air: 0 }
} as MonitoringData<T>;
} else {
throw new Error(`Nieznany typ systemu: ${(this.system as any).type}`);
}
}
// Metoda pomocnicza do inicjalizacji zalecanych działań
private initializeRecommendedActions(): RecommendedActions<T> {
if (this.system.status === "error") {
return {
severity: "high",
actions: ["Natychmiastowa interwencja techniczna", "Powiadomienie kierownictwa"],
escalation: "Dyrektor ds. technicznych",
timeToResolve: 60 // minut
} as RecommendedActions<T>;
} else if (this.system.status === "maintenance") {
return {
checklistItems: ["Sprawdzenie okablowania", "Test funkcjonalności"],
estimatedCompletionTime: new Date(Date.now() + 3600000), // +1 godzina
personnelAssigned: ["Tech-1", "Tech-2"]
} as RecommendedActions<T>;
} else if (this.system.status === "offline") {
return {
restartProcedures: ["Kontrola zasilania", "Reset systemu"],
systemDependencies: ["Główne zasilanie"],
estimatedDowntime: 120 // minut
} as RecommendedActions<T>;
} else {
return {
routineChecks: ["Codzienny przegląd", "Sprawdzenie logów"],
nextMaintenanceDate: new Date(Date.now() + 7 * 24 * 3600000) // +7 dni
} as RecommendedActions<T>;
}
}
// Metoda aktualizująca dane monitorowania
updateMonitoringData(newData: Partial<MonitoringData<T>>): void {
this.monitoringData = { ...this.monitoringData, ...newData };
console.log(`Zaktualizowano dane monitorowania dla ${this.system.name} (ID: ${this.system.id})`);
}
// Metoda generująca raport systemu
generateSystemReport(): string {
const report = `
RAPORT SYSTEMU: ${this.system.name.toUpperCase()} (ID: ${this.system.id})
=========================================================
Typ: ${this.system.type}
Status: ${this.system.status}
Ostatnia aktualizacja: ${this.system.lastUpdated.toLocaleString()}
SZCZEGÓŁY MONITOROWANIA:
${this.formatMonitoringData()}
ZALECANE DZIAŁANIA:
${this.formatRecommendedActions()}
=========================================================
Raport wygenerowany: ${new Date().toLocaleString()}
`;
return report;
}
// Metoda formatująca dane monitorowania zależnie od typu systemu
private formatMonitoringData(): string {
if (this.system.type === "security") {
const data = this.monitoringData as MonitoringData<SecuritySystem>;
return `
Wykryte naruszenia: ${data.breachDetections}
Aktywne alarmy: ${data.activeAlarms.length > 0 ? data.activeAlarms.join(", ") : "Brak"}
Nagrania bezpieczeństwa: ${data.securityFootage.length}
`;
} else if (this.system.type === "power") {
const data = this.monitoringData as MonitoringData<PowerSystem>;
return `
Efektywność energetyczna: ${data.energyEfficiency}%
Szacowany czas na zasilaniu awaryjnym: ${data.estimatedBackupTime} godzin
Fluktuacje mocy: ${data.powerFluctuations ? "TAK" : "NIE"}
Rozkład obciążenia: ${data.loadDistribution.map(d => `${d.sector}: ${d.load}kW`).join(", ")}
`;
} else if (this.system.type === "transport") {
const data = this.monitoringData as MonitoringData<TransportSystem>;
return `
Aktywne pojazdy: ${data.activeVehicles}
Liczba pasażerów: ${data.passengerCount}
Zużycie paliwa: ${data.fuelConsumption} litrów/godz.
Raporty opóźnień: ${data.delayReports.length > 0
? data.delayReports.map(d => `${d.routeId}: ${d.delay}min`).join(", ")
: "Brak opóźnień"}
`;
} else if (this.system.type === "lifesupport") {
const data = this.monitoringData as MonitoringData<LifeSupportSystem>;
return `
Warunki w habitatach: ${data.habitatConditions.map(h =>
`${h.habitatId} (Temp: ${h.temperature}°C, Wilg: ${h.humidity}%, O2: ${h.oxygenLevel}%)`).join("\n")}
Wykryte anomalie: ${data.anomalyDetections.length > 0 ? data.anomalyDetections.join(", ") : "Brak"}
Zużycie zasobów: Woda: ${data.resourceConsumption.water}m³, Prąd: ${data.resourceConsumption.electricity}kWh, Powietrze: ${data.resourceConsumption.air}m³
`;
} else {
return `Brak danych monitorowania dla tego typu systemu.`;
}
}
// Metoda formatująca zalecane działania zależnie od statusu systemu
private formatRecommendedActions(): string {
if (this.system.status === "error") {
const actions = this.recommendedActions as RecommendedActions<{ status: "error" }>;
return `
Poziom ważności: ${actions.severity}
Zalecane działania: ${actions.actions.join(", ")}
Eskalacja do: ${actions.escalation}
Szacowany czas naprawy: ${actions.timeToResolve} minut
`;
} else if (this.system.status === "maintenance") {
const actions = this.recommendedActions as RecommendedActions<{ status: "maintenance" }>;
return `
Elementy do sprawdzenia: ${actions.checklistItems.join(", ")}
Szacowany czas zakończenia: ${actions.estimatedCompletionTime.toLocaleString()}
Przydzielony personel: ${actions.personnelAssigned.join(", ")}
`;
} else if (this.system.status === "offline") {
const actions = this.recommendedActions as RecommendedActions<{ status: "offline" }>;
return `
Procedury restartu: ${actions.restartProcedures.join(", ")}
Zależności systemowe: ${actions.systemDependencies.join(", ")}
Szacowany czas przestoju: ${actions.estimatedDowntime} minut
`;
} else {
const actions = this.recommendedActions as RecommendedActions<ParkSystem>;
return `
Rutynowe kontrole: ${actions.routineChecks.join(", ")}
Następny przegląd: ${actions.nextMaintenanceDate.toLocaleDateString()}
`;
}
}
// Metoda zwracająca zalecane działania
getRecommendedActions(): RecommendedActions<T> {
return this.recommendedActions;
}
// Metoda aktualizująca status systemu
updateSystemStatus(newStatus: SystemStatus): void {
(this.system as any).status = newStatus;
this.system.lastUpdated = new Date();
// Aktualizacja zalecanych działań po zmianie statusu
this.recommendedActions = this.initializeRecommendedActions();
console.log(`Zaktualizowano status systemu ${this.system.name} na ${newStatus}`);
}
}
// --- Przykład użycia ---
// Tworzenie przykładowych systemów
const securitySystem: SecuritySystem = {
id: "SEC-001",
name: "Główny system bezpieczeństwa",
status: "online",
lastUpdated: new Date(),
type: "security",
enclosures: ["T-Rex", "Velociraptor", "Dilophosaurus"],
alertLevel: "low",
cameras: 24,
motionSensors: 36
};
const powerSystem: PowerSystem = {
id: "PWR-001",
name: "Główny system zasilania",
status: "online",
lastUpdated: new Date(),
type: "power",
outputCapacity: 10000,
currentLoad: 6500,
backupCapacity: 5000,
generators: 4
};
// Tworzenie monitorów dla różnych systemów
const securityMonitor = new SystemMonitor<SecuritySystem>(securitySystem);
const powerMonitor = new SystemMonitor<PowerSystem>(powerSystem);
// Aktualizacja danych monitorowania
securityMonitor.updateMonitoringData({
breachDetections: 3,
activeAlarms: ["Sektor 7G", "Północne ogrodzenie"],
securityFootage: [
{ cameraId: "CAM-12", timestamp: new Date(), events: ["Ruch w obszarze zastrzeżonym"] }
]
});
powerMonitor.updateMonitoringData({
loadDistribution: [
{ sector: "Visitor Center", load: 2000 },
{ sector: "TRex Paddock", load: 1500 },
{ sector: "Raptor Enclosure", load: 1800 },
{ sector: "Labs", load: 1200 }
],
energyEfficiency: 92,
powerFluctuations: true
});
// Symulacja awarii systemu zasilania
powerMonitor.updateSystemStatus("error");
// Generowanie raportów
console.log(securityMonitor.generateSystemReport());
console.log(powerMonitor.generateSystemReport());
// Sprawdzamy, czy zalecane działania są poprawnego typu
const powerActions = powerMonitor.getRecommendedActions();
console.log(`Poziom ważności awarii zasilania: ${powerActions.severity}`);
console.log(`Czas do rozwiązania: ${powerActions.timeToResolve} minut`);Ten rozbudowany przykład pokazuje, jak typy warunkowe mogą być wykorzystane do stworzenia skomplikowanego systemu, który dostosowuje swoje zachowanie i strukturę danych w zależności od typu obiektu, nad którym pracuje. Jest to szczególnie przydatne w modelowaniu systemów, które mają wiele wariantów, ale współdzielą pewną wspólną funkcjonalność.
Ograniczenia typów warunkowych
Mimo że typy warunkowe są potężnym narzędziem, mają również pewne ograniczenia:
Ograniczona zdolność wnioskowania - TypeScript ma ograniczoną zdolność wnioskowania o typach w złożonych scenariuszach, szczególnie kiedy używane są typy generyczne razem z typami warunkowymi.
Type erasure w czasie wykonania - podobnie jak inne zaawansowane funkcje typów w TypeScript, typy warunkowe istnieją tylko w czasie kompilacji. W czasie wykonania nie ma informacji o typach warunkowych, co może prowadzić do trudności w implementacji niektórych wzorców.
Złożoność dla początkujących - typy warunkowe, szczególnie w połączeniu z innymi zaawansowanymi funkcjami typów, mogą być trudne do zrozumienia dla osób początkujących w TypeScript.
Kiedy używać typów warunkowych?
Typy warunkowe są szczególnie przydatne w następujących scenariuszach:
Tworzenie elastycznych API - gdy chcesz, aby twoje funkcje lub metody zachowywały się różnie w zależności od typu przekazanych argumentów.
Implementacja zaawansowanych narzędzi generycznych - gdy budujesz skomplikowane narzędzia, które muszą działać z różnymi typami danych.
Modelowanie złożonych systemów biznesowych - gdy masz do czynienia z różnymi wariantami obiektów biznesowych, które mają wspólne cechy, ale różnią się w szczegółach.
Tworzenie narzędzi transformacji typów - gdy potrzebujesz mapować jedne typy na inne w sposób warunkowy.
Podsumowanie
Typy warunkowe w TypeScript są zaawansowanym, ale niezwykle przydatnym narzędziem, które pozwala na tworzenie elastycznych i typowo bezpiecznych API. Podobnie jak genetycy w Parku Jurajskim mogą dostosować swoje protokoły do różnych typów DNA dinozaurów, typy warunkowe pozwalają nam dostosować zachowanie naszego kodu do różnych typów danych, zachowując przy tym pełne wsparcie dla statycznego typowania.
W następnych ćwiczeniach będziemy kontynuować eksplorację zaawansowanych funkcji systemu typów TypeScript i zobaczymy, jak mogą one pomóc nam w tworzeniu bezpieczniejszego, bardziej elastycznego i łatwiejszego w utrzymaniu kodu.
Kod do tej lekcji: index.ts
// Typy warunkowe (Conditional Types) - Park Jurajski
console.log("=== TYPY WARUNKOWE ===\n");
// ===========================================
// 1. Podstawowy typ warunkowy
// ===========================================
type IsCarnivore<T> = T extends { diet: "carnivore" } ? true : false;
interface Carnivore {
name: string;
diet: "carnivore";
biteForce: number;
}
interface Herbivore {
name: string;
diet: "herbivore";
favoriteFood: string;
}
// Typ warunkowy rozwiazuje sie w kompilacji
type RexCheck = IsCarnivore<Carnivore>; // true
type CeraCheck = IsCarnivore<Herbivore>; // false
// ===========================================
// 2. Extract i Exclude
// ===========================================
type DinosaurType = "T-Rex" | "Velociraptor" | "Triceratops" | "Brachiosaurus" | "Stegosaurus";
// Extract - wyciaganie typow pasujacych
type Predator = Extract<DinosaurType, "T-Rex" | "Velociraptor">;
// Wynik: "T-Rex" | "Velociraptor"
// Exclude - usuwanie typow pasujacych
type Gentle = Exclude<DinosaurType, "T-Rex" | "Velociraptor">;
// Wynik: "Triceratops" | "Brachiosaurus" | "Stegosaurus"
// ===========================================
// 3. infer - wyciaganie typow z konstruktow
// ===========================================
type DinosaurData = {
name: string;
stats: { weight: number; height: number; speed: number };
abilities: string[];
};
// Wyciaganie typu z zagniezdzonej struktury
type StatsType = DinosaurData["stats"]; // { weight: number; height: number; speed: number }
// infer w typach warunkowych
type UnpackArray<T> = T extends Array<infer U> ? U : T;
type AbilityType = UnpackArray<DinosaurData["abilities"]>; // string
type UnpackPromise<T> = T extends Promise<infer U> ? U : T;
type ResolvedDino = UnpackPromise<Promise<DinosaurData>>; // DinosaurData
// ===========================================
// 4. ReturnType i Parameters
// ===========================================
function createDinosaur(name: string, weight: number, isDangerous: boolean) {
return {
name,
weight,
isDangerous,
createdAt: new Date()
};
}
type DinoResult = ReturnType<typeof createDinosaur>;
type DinoParams = Parameters<typeof createDinosaur>;
// ===========================================
// 5. NonNullable
// ===========================================
type MaybeDino = string | number | null | undefined;
type DefinitelyDino = NonNullable<MaybeDino>; // string | number
// ===========================================
// 6. Praktyczny przyklad - system odpowiedzi API
// ===========================================
type ApiResponse<T> = T extends "dinosaur"
? { id: number; name: string; species: string }
: T extends "enclosure"
? { id: number; name: string; capacity: number }
: T extends "staff"
? { id: number; name: string; role: string }
: never;
function getResponse<T extends "dinosaur" | "enclosure" | "staff">(
type: T
): ApiResponse<T> {
if (type === "dinosaur") {
return { id: 1, name: "Rexy", species: "T-Rex" } as ApiResponse<T>;
} else if (type === "enclosure") {
return { id: 101, name: "Strefa T-Rex", capacity: 2 } as ApiResponse<T>;
}
return { id: 1001, name: "Alan Grant", role: "Paleontolog" } as ApiResponse<T>;
}
// ===========================================
// Test
// ===========================================
console.log("--- Extract / Exclude ---");
const predator: Predator = "T-Rex";
const gentle: Gentle = "Brachiosaurus";
console.log("Drapieznik:", predator);
console.log("Lagodny:", gentle);
console.log("\n--- ReturnType ---");
const dino: DinoResult = createDinosaur("Blue", 15, true);
console.log("Stworzony dinozaur:", JSON.stringify(dino, null, 2));
console.log("\n--- Conditional API Response ---");
const dinoResp = getResponse("dinosaur");
console.log("Dinozaur:", JSON.stringify(dinoResp));
const encResp = getResponse("enclosure");
console.log("Zagodzenie:", JSON.stringify(encResp));
const staffResp = getResponse("staff");
console.log("Pracownik:", JSON.stringify(staffResp));
console.log("\n--- NonNullable ---");
function processDino(value: NonNullable<MaybeDino>): void {
console.log("Wartosc:", value, "Typ:", typeof value);
}
processDino("Rexy");
processDino(42);
// processDino(null); // Error!
console.log("\nTypy warunkowe = dynamiczna logika na poziomie 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. Co robi typ warunkowy T extends U ? X : Y w TypeScript?
2. Do czego służy słowo kluczowe infer w conditional types?
To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.
Zadania praktyczne w grze
- Edytor kodu
Stwórz conditional types do dynamicznej inferencji typów
- Klikanie w kolejności
Ułóż elementy conditional type: