Kurs JavaScript i TypeScript · Moduł 10: TypeScript w praktyce

Projekt końcowy: System diagnostyczny Parku Jurajskiego

11 min czytania ·
W tej lekcji4

"Dotarliśmy do końca naszej podróży," ogłasza Dr. Ellie Sattler, stojąc w głównym laboratorium diagnostycznym InGen. "Przez ten moduł opanowałeś Web Workers, zarządzanie pamięcią, zaawansowane typy TypeScript - od utility types, przez conditional i mapped types, po template literal types i module augmentation. Nauczyłeś się też Test-Driven Development i integracji TypeScript z popularnymi frameworkami."

"Teraz zbudujesz kompletny system diagnostyczny Parku Jurajskiego - projekt, który połączy wszystkie te umiejętności w jeden, spójny system. Potraktuj to jako symulację prawdziwego, produkcyjnego kodu, który mógłby działać w naszym parku."

W tym projekcie stworzysz zaawansowany system diagnostyczny łączący: typowanie na poziomie eksperta z utility types i conditional types, template literal types do generowania API, mapped types do transformacji danych, module augmentation do rozszerzania istniejących bibliotek oraz podejście TDD z testami jednostkowymi.

Cel projektu

Zbudujesz system DiagnosticCenter, który:

  • Wykorzystuje zaawansowane utility types do precyzyjnego modelowania danych
  • Stosuje conditional types do automatycznego wyboru strategii diagnostycznej
  • Używa template literal types do budowania type-safe API
  • Implementuje mapped types do transformacji danych diagnostycznych
  • Rozszerza istniejące moduły przez module augmentation
  • Jest pisany w podejściu TDD z testami jednostkowymi

Wymagania funkcjonalne

1. Zaawansowane Utility Types dla danych diagnostycznych

Zdefiniuj precyzyjne typy danych, wykorzystując zarówno wbudowane, jak i własne utility types. System musi obsługiwać różne kategorie dinozaurów z różnymi zestawami parametrów diagnostycznych.

// Bazowy typ dinozaura
interface DinosaurRecord {
  id: string;
  species: string;
  name: string;
  age: number;
  weight: number;
  height: number;
  enclosureId: string;
  diet: 'carnivore' | 'herbivore' | 'omnivore';
  healthStatus: 'healthy' | 'sick' | 'critical' | 'quarantined';
  lastCheckup: Date;
  geneticModifications: string[];
  dangerRating: 1 | 2 | 3 | 4 | 5;
}

// Własne utility types
type DeepReadonly<T> = {
  readonly [K in keyof T]: T[K] extends object
    ? T[K] extends Date | Array<any>
      ? T[K]
      : DeepReadonly<T[K]>
    : T[K];
};

type RequireAtLeastOne<T, Keys extends keyof T = keyof T> =
  Pick<T, Exclude<keyof T, Keys>> &
  { [K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>> }[Keys];

type Mutable<T> = {
  -readonly [K in keyof T]: T[K];
};

// Zablokowany rekord - nie można modyfikować po zamknięciu diagnostyki
type LockedDiagnosticRecord = DeepReadonly<DinosaurRecord>;

// Aktualizacja - wymagaj co najmniej jednego pola
type DinosaurUpdate = RequireAtLeastOne<
  Partial<Pick<DinosaurRecord, 'healthStatus' | 'weight' | 'enclosureId' | 'dangerRating'>>,
  'healthStatus' | 'weight' | 'enclosureId' | 'dangerRating'
>;

// Rekord do wyświetlania - zamień Date na string
type DisplayRecord<T> = {
  [K in keyof T]: T[K] extends Date ? string : T[K];
};

type DinosaurDisplayRecord = DisplayRecord<DinosaurRecord>;

// Filtrowanie pól numerycznych
type NumericFields<T> = {
  [K in keyof T as T[K] extends number ? K : never]: T[K];
};

type DinosaurMetrics = NumericFields<DinosaurRecord>;
// Rezultat: { age: number; weight: number; height: number; dangerRating: 1|2|3|4|5 }

2. Conditional Types dla strategii diagnostycznych

Wykorzystaj typy warunkowe do automatycznego określania procedury diagnostycznej na podstawie gatunku i stanu zdrowia dinozaura. System musi "wiedzieć" na poziomie typów, jakie badania przeprowadzić.

// Typy gatunków
type CarnivoreSpecies = 'TRex' | 'Velociraptor' | 'Spinosaurus' | 'Dilophosaurus';
type HerbivoreSpecies = 'Triceratops' | 'Brachiosaurus' | 'Stegosaurus' | 'Parasaurolophus';
type FlyingSpecies = 'Pteranodon' | 'Dimorphodon';
type AquaticSpecies = 'Mosasaurus' | 'Plesiosaurus';

type AllSpecies = CarnivoreSpecies | HerbivoreSpecies | FlyingSpecies | AquaticSpecies;

// Conditional type - procedura diagnostyczna zależy od gatunku
type DiagnosticProcedure<S extends AllSpecies> =
  S extends CarnivoreSpecies ? {
    type: 'carnivore-diagnostic';
    sedationRequired: true;
    aggressionTest: boolean;
    teethInspection: boolean;
    clawMeasurement: boolean;
    huntingBehaviorAnalysis: boolean;
  } :
  S extends HerbivoreSpecies ? {
    type: 'herbivore-diagnostic';
    sedationRequired: false;
    digestiveAnalysis: boolean;
    hoofInspection: boolean;
    grazingPatternCheck: boolean;
  } :
  S extends FlyingSpecies ? {
    type: 'flying-diagnostic';
    sedationRequired: true;
    wingspanMeasurement: number;
    flightCapabilityTest: boolean;
    nestInspection: boolean;
  } :
  S extends AquaticSpecies ? {
    type: 'aquatic-diagnostic';
    sedationRequired: true;
    underwaterExam: boolean;
    gillFunction: boolean;
    divingDepthTest: number;
  } :
  never;

// Wynik diagnostyki - zależny od procedury
type DiagnosticResult<S extends AllSpecies> = {
  species: S;
  procedure: DiagnosticProcedure<S>;
  timestamp: Date;
  veterinarian: string;
  passed: boolean;
  notes: string;
};

// Użycie - TypeScript wymusza odpowiednie pola
const trexDiagnostic: DiagnosticResult<'TRex'> = {
  species: 'TRex',
  procedure: {
    type: 'carnivore-diagnostic',
    sedationRequired: true,
    aggressionTest: true,
    teethInspection: true,
    clawMeasurement: true,
    huntingBehaviorAnalysis: false
  },
  timestamp: new Date(),
  veterinarian: 'Dr. Harding',
  passed: true,
  notes: 'T-Rex w doskonałej formie. Sedacja przebiegła bez komplikacji.'
};

// Conditional type z infer - wyciągnij typ procedury
type ExtractProcedureType<T> =
  T extends DiagnosticResult<infer S>
    ? DiagnosticProcedure<S>
    : never;

// Dystrybucyjny conditional type - filtrowanie gatunków wymagających sedacji
type RequiresSedation<S extends AllSpecies> =
  DiagnosticProcedure<S> extends { sedationRequired: true } ? S : never;

type SedatedSpecies = RequiresSedation<AllSpecies>;
// Rezultat: 'TRex' | 'Velociraptor' | ... (wszystkie wymagające sedacji)

3. Template Literal Types dla type-safe API

Stwórz system API, który na poziomie typów gwarantuje poprawność nazw endpointów, kluczy konfiguracji i komunikatów diagnostycznych.

// Template literal types dla endpointów API
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
type ApiVersion = 'v1' | 'v2';
type Resource = 'dinosaurs' | 'enclosures' | 'diagnostics' | 'alerts';

// Automatyczne generowanie ścieżek API
type ApiEndpoint = `/api/${ApiVersion}/${Resource}`;
// Rezultat: "/api/v1/dinosaurs" | "/api/v1/enclosures" | ... (12 kombinacji)

type ApiEndpointWithId = `${ApiEndpoint}/${string}`;

// Template literal types dla kluczy konfiguracji
type SensorType = 'temperature' | 'heartRate' | 'movement' | 'stress';
type SensorLocation = 'head' | 'body' | 'tail' | 'legs';

type SensorConfigKey = `sensor_${SensorType}_${SensorLocation}`;
// Rezultat: "sensor_temperature_head" | "sensor_temperature_body" | ... (16 kombinacji)

type SensorConfig = Record<SensorConfigKey, {
  enabled: boolean;
  threshold: number;
  interval: number;
}>;

// Template literal types dla komunikatów diagnostycznych
type DiagnosticStatus = 'started' | 'completed' | 'failed' | 'cancelled';
type DiagnosticMessage<S extends AllSpecies, D extends DiagnosticStatus> =
  `[DIAGNOSTIC] Species: ${S} | Status: ${D}`;

// Użycie
const message: DiagnosticMessage<'TRex', 'completed'> =
  '[DIAGNOSTIC] Species: TRex | Status: completed';

// Ekstrakcja z template literal type
type ExtractSpecies<T> = T extends `[DIAGNOSTIC] Species: ${infer S} | Status: ${string}`
  ? S
  : never;

type ExtractedSpecies = ExtractSpecies<typeof message>; // "TRex"

// Zaawansowane: konwersja camelCase na kebab-case
type CamelToKebab<S extends string> =
  S extends `${infer First}${infer Rest}`
    ? Rest extends Uncapitalize<Rest>
      ? `${Lowercase<First>}${CamelToKebab<Rest>}`
      : `${Lowercase<First>}-${CamelToKebab<Rest>}`
    : S;

type TestKebab = CamelToKebab<'healthStatus'>; // "health-status"
type TestKebab2 = CamelToKebab<'dangerRating'>; // "danger-rating"

4. Mapped Types do transformacji i generowania typów

Wykorzystaj mapped types do automatycznego generowania formularzy, walidatorów i transformacji danych diagnostycznych.

// Mapped type: generuj typ formularza z modelu danych
type FormFields<T> = {
  [K in keyof T]: {
    value: T[K];
    label: string;
    required: boolean;
    validate: (value: T[K]) => boolean;
  };
};

type DinosaurForm = FormFields<Pick<DinosaurRecord, 'name' | 'species' | 'weight' | 'healthStatus'>>;

// Mapped type: generuj typ walidatora
type Validators<T> = {
  [K in keyof T as `validate${Capitalize<K & string>}`]: (value: T[K]) => boolean;
};

type DinosaurValidators = Validators<Pick<DinosaurRecord, 'name' | 'age' | 'weight'>>;
// Rezultat: {
//   validateName: (value: string) => boolean;
//   validateAge: (value: number) => boolean;
//   validateWeight: (value: number) => boolean;
// }

// Mapped type: generuj gettery i settery
type Accessors<T> = {
  [K in keyof T as `get${Capitalize<K & string>}`]: () => T[K];
} & {
  [K in keyof T as `set${Capitalize<K & string>}`]: (value: T[K]) => void;
};

type DinosaurAccessors = Accessors<Pick<DinosaurRecord, 'name' | 'healthStatus'>>;
// Rezultat: {
//   getName: () => string;
//   setName: (value: string) => void;
//   getHealthStatus: () => 'healthy' | 'sick' | 'critical' | 'quarantined';
//   setHealthStatus: (value: ...) => void;
// }

// Mapped type: zamień wartości na Observable
type Observable<T> = {
  [K in keyof T]: {
    value: T[K];
    subscribe: (callback: (newValue: T[K], oldValue: T[K]) => void) => void;
    unsubscribe: (callback: Function) => void;
  };
};

type ObservableDinosaurMetrics = Observable<DinosaurMetrics>;

// Implementacja mapped type w runtime
function createValidators<T extends Record<string, any>>(
  rules: { [K in keyof T]: (value: T[K]) => boolean }
): Validators<T> {
  const validators = {} as any;
  for (const key in rules) {
    const capitalizedKey = key.charAt(0).toUpperCase() + key.slice(1);
    validators[`validate${capitalizedKey}`] = rules[key];
  }
  return validators;
}

// Przykład użycia
const dinoValidators = createValidators<Pick<DinosaurRecord, 'name' | 'age' | 'weight'>>({
  name: (value) => value.length >= 2 && value.length <= 50,
  age: (value) => value > 0 && value < 200,
  weight: (value) => value > 0 && value < 100000
});

5. Module Augmentation i Test-Driven Development

Rozszerz istniejące typy przez module augmentation i napisz system z podejściem TDD - najpierw testy, potem implementacja.

// Module augmentation - rozszerzanie istniejącego modułu
declare module './dinosaur-record' {
  interface DinosaurRecord {
    lastDiagnosticId?: string;
    diagnosticHistory: DiagnosticEntry[];
    riskScore: number;
  }
}

interface DiagnosticEntry {
  id: string;
  date: Date;
  type: string;
  result: 'pass' | 'fail' | 'inconclusive';
  veterinarian: string;
}

// TDD - najpierw piszemy testy
// Test 1: DiagnosticCenter powinien obliczyć ryzyko
function testCalculateRiskScore() {
  const center = new DiagnosticCenter();

  // Zdrowy roślinożerca - niskie ryzyko
  const herbivoreRisk = center.calculateRiskScore({
    diet: 'herbivore',
    healthStatus: 'healthy',
    dangerRating: 1,
    age: 5
  } as DinosaurRecord);

  console.assert(herbivoreRisk < 30,
    `Oczekiwano ryzyko < 30, otrzymano ${herbivoreRisk}`);

  // Chory drapieżnik - wysokie ryzyko
  const carnivoreRisk = center.calculateRiskScore({
    diet: 'carnivore',
    healthStatus: 'sick',
    dangerRating: 5,
    age: 12
  } as DinosaurRecord);

  console.assert(carnivoreRisk > 70,
    `Oczekiwano ryzyko > 70, otrzymano ${carnivoreRisk}`);

  console.log('testCalculateRiskScore: PASSED');
}

// Test 2: System powinien filtrować dinozaury wymagające badania
function testFilterDinosRequiringCheckup() {
  const center = new DiagnosticCenter();

  const dinosaurs: Partial<DinosaurRecord>[] = [
    { name: 'Rex', lastCheckup: new Date('2024-01-01'), healthStatus: 'healthy' },
    { name: 'Blue', lastCheckup: new Date('2025-12-01'), healthStatus: 'healthy' },
    { name: 'Echo', lastCheckup: new Date('2025-12-15'), healthStatus: 'critical' }
  ];

  const needCheckup = center.filterRequiringCheckup(
    dinosaurs as DinosaurRecord[],
    30 // Dni od ostatniego badania
  );

  // Rex - badanie ponad 30 dni temu
  // Echo - status "critical" wymaga natychmiastowego badania
  console.assert(needCheckup.length === 2,
    `Oczekiwano 2 dinozaury, otrzymano ${needCheckup.length}`);

  console.log('testFilterDinosRequiringCheckup: PASSED');
}

// Test 3: Generowanie raportu powinno zwracać prawidłowy format
function testGenerateReport() {
  const center = new DiagnosticCenter();

  const report = center.generateReport('TRex', {
    species: 'TRex',
    procedure: {
      type: 'carnivore-diagnostic',
      sedationRequired: true,
      aggressionTest: true,
      teethInspection: true,
      clawMeasurement: true,
      huntingBehaviorAnalysis: false
    },
    timestamp: new Date(),
    veterinarian: 'Dr. Harding',
    passed: true,
    notes: 'Badanie zakończone pomyślnie'
  });

  console.assert(report.includes('[DIAGNOSTIC]'),
    'Raport powinien zawierać nagłówek [DIAGNOSTIC]');
  console.assert(report.includes('TRex'),
    'Raport powinien zawierać gatunek');
  console.assert(report.includes('Dr. Harding'),
    'Raport powinien zawierać weterynarza');

  console.log('testGenerateReport: PASSED');
}

// Implementacja (po napisaniu testów)
class DiagnosticCenter {
  calculateRiskScore(dino: Pick<DinosaurRecord, 'diet' | 'healthStatus' | 'dangerRating' | 'age'>): number {
    let score = 0;

    // Dieta wpływa na bazowe ryzyko
    const dietScores = { carnivore: 30, omnivore: 15, herbivore: 5 };
    score += dietScores[dino.diet];

    // Stan zdrowia
    const healthScores = { healthy: 0, sick: 20, critical: 40, quarantined: 30 };
    score += healthScores[dino.healthStatus];

    // Poziom zagrożenia (1-5) * 6
    score += dino.dangerRating * 6;

    // Wiek - starsze dinozaury są bardziej nieprzewidywalne
    if (dino.age > 10) score += 10;

    return Math.min(100, Math.max(0, score));
  }

  filterRequiringCheckup(dinosaurs: DinosaurRecord[], maxDaysSinceCheckup: number): DinosaurRecord[] {
    const now = new Date();
    return dinosaurs.filter(dino => {
      // Krytyczny stan - zawsze wymaga badania
      if (dino.healthStatus === 'critical') return true;

      // Sprawdź czas od ostatniego badania
      const daysSinceCheckup = Math.floor(
        (now.getTime() - dino.lastCheckup.getTime()) / (1000 * 60 * 60 * 24)
      );
      return daysSinceCheckup > maxDaysSinceCheckup;
    });
  }

  generateReport<S extends AllSpecies>(
    species: S,
    result: DiagnosticResult<S>
  ): string {
    return [
      `[DIAGNOSTIC] Species: ${species} | Status: ${result.passed ? 'completed' : 'failed'}`,
      `Weterynarz: ${result.veterinarian}`,
      `Data: ${result.timestamp.toISOString()}`,
      `Wynik: ${result.passed ? 'POZYTYWNY' : 'NEGATYWNY'}`,
      `Notatki: ${result.notes}`
    ].join('\n');
  }
}

// Uruchomienie testów
testCalculateRiskScore();
testFilterDinosRequiringCheckup();
testGenerateReport();

Wskazówki implementacyjne

Zacznij od zdefiniowania bazowych typów i interfejsów - to fundament Twojego systemu diagnostycznego. Następnie zbuduj conditional types dla procedur diagnostycznych, template literal types dla API i mapped types dla transformacji. Na końcu napisz testy i implementację DiagnosticCenter.

Sugerowana kolejność implementacji:

// 1. Typy bazowe: DinosaurRecord, AllSpecies
// 2. Utility types: DeepReadonly, RequireAtLeastOne, NumericFields
// 3. Conditional types: DiagnosticProcedure<S>, DiagnosticResult<S>
// 4. Template literal types: ApiEndpoint, SensorConfigKey
// 5. Mapped types: FormFields, Validators, Accessors
// 6. Module augmentation: rozszerzenie DinosaurRecord
// 7. Testy jednostkowe (TDD)
// 8. Implementacja DiagnosticCenter
// 9. Integracja i uruchomienie testów

Pamiętaj o kluczowych zasadach:

  • Utility types służą do transformacji istniejących typów - nie twórz nowych typów od zera, gdy możesz przekształcić istniejące
  • Conditional types z infer pozwalają wyciągać typy z zagnieżdżonych struktur
  • Template literal types gwarantują poprawność stringów na poziomie kompilacji
  • Mapped types z as pozwalają na zmianę nazw kluczy (remapping)
  • Module augmentation wymaga declare module i merge'uje się z oryginalnym typem
  • TDD oznacza: napisz test → uruchom (czerwony) → zaimplementuj → uruchom (zielony) → refaktoruj

Powodzenia!

"Pamiętaj," mówi Dr. Sattler z uśmiechem, "w Parku Jurajskim nie ma miejsca na błędy typów. Każdy any to potencjalna luka w zabezpieczeniach, każdy brakujący typ to otwarta brama zagrody. TypeScript daje Ci narzędzia, aby złapać 90% błędów jeszcze zanim kod zostanie uruchomiony. Utility types, conditional types, mapped types, template literal types - to Twój arsenał. Użyj go mądrze."

"A testy? Testy to jak systemy alarmowe w zagrodach. Nie budujesz ich po tym, jak T-Rex ucieknie. Budujesz je ZANIM to się stanie. TDD to filozofia, która chroni Twój kod przed katastrofą."

Otwórz edytor i zbuduj swój system diagnostyczny - kompletny, w pełni typowany i przetestowany!

Kod do tej lekcji: index.ts
// Projekt koncowy: System diagnostyczny Parku Jurajskiego
// Polacz: utility types, conditional types, mapped types, template literal types, TDD

// === 1. ZAAWANSOWANE UTILITY TYPES ===
interface DinosaurRecord {
  id: string;
  species: string;
  name: string;
  age: number;
  weight: number;
  diet: "carnivore" | "herbivore" | "omnivore";
  healthStatus: "healthy" | "sick" | "critical";
  enclosureId: string;
  dangerRating: 1 | 2 | 3 | 4 | 5;
}

// TODO: Stworz DeepReadonly<T> - rekurencyjne readonly
type DeepReadonly<T> = {
  // TODO: Uzyj mapped types z warunkiem dla obiektow zagniezdrzonych
  readonly [K in keyof T]: T[K];
};

// TODO: Stworz RequireAtLeastOne<T> - wymaga co najmniej jednego pola
// TODO: Stworz Mutable<T> - usuwa readonly z pol

// === 2. CONDITIONAL TYPES ===
// TODO: Stworz typ DiagnosticStrategy<T>
// Jezeli diet = "carnivore" -> wymaga: bitePressureTest, aggressionLevel
// Jezeli diet = "herbivore" -> wymaga: foliagePreference, migrationPattern
type DiagnosticStrategy<T extends DinosaurRecord["diet"]> =
  // TODO: Zaimplementuj warunek
  T extends "carnivore" ? { bitePressureTest: number; aggressionLevel: number }
  : { foliagePreference: string[]; migrationPattern: string };

// === 3. TEMPLATE LITERAL TYPES ===
// TODO: Stworz type-safe API endpointy
type Endpoint = "dinosaurs" | "enclosures" | "alerts";
type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";

// TODO: Stworz typ ApiRoute = "${HttpMethod} /api/${Endpoint}"
// TODO: Stworz funkcje handleRequest(route: ApiRoute): void

// === 4. MAPPED TYPES DLA DIAGNOSTYKI ===
// TODO: Stworz typ DiagnosticForm<T> ktory zamienia wszystkie pola na formowe
// np. { name: string } -> { name: { value: string; isValid: boolean; error?: string } }

// === 5. PROSTY SYSTEM TESTOWY (symulacja TDD) ===
// TODO: Stworz funkcje testowe sprawdzajace poprawnosc systemu
function assertEqual<T>(actual: T, expected: T, testName: string): void {
  const passed = JSON.stringify(actual) === JSON.stringify(expected);
  console.log(passed ? `PASS: ${testName}` : `FAIL: ${testName}`);
  if (!passed) {
    console.log(`  Expected: ${JSON.stringify(expected)}`);
    console.log(`  Actual:   ${JSON.stringify(actual)}`);
  }
}

// TODO: Napisz testy dla systemu diagnostycznego
// Test 1: Rejestracja dinozaura
// Test 2: Diagnostyka miesozercy vs roslinozercy
// Test 3: Generowanie raportu
// Test 4: Walidacja danych wejsciowych

console.log("System diagnostyczny - uruchom testy!");

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

  1. Projekt do wysłaniaProjekt do mentora: Moduł 10
  2. WideoVideo: Podsumowanie modułu

Przydatne artykuły