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

TypeScript z popularnymi frameworkami

13 min czytania ·
W tej lekcji5

"Witaj z powrotem w Parku Jurajskim" - mówi Dr. Rex. "Poznałeś już TypeScript jako samodzielny język, ale w prawdziwym świecie rzadko używamy go w czystej postaci. Zwykle łączymy go z frameworkami, które pomagają budować złożone aplikacje." Bez typów literówka w nazwie propa wyjdzie dopiero wtedy, gdy karta Velociraptora pokaże napis Bezpieczny.

TypeScript z React - Komponenty z typami

React to jedna z najpopularniejszych bibliotek do budowania interfejsów użytkownika. TypeScript świetnie się z nią integruje, zapewniając silne typowanie komponentów, props i hooków.

Podstawowe komponenty funkcyjne

Props opisujesz interfejsem, w którym znak ? oznacza pole opcjonalne, a komponent dostaje typ React.FC<DinoCardProps>:

// Interfejs dla props komponentu
interface DinoCardProps {
  name: string;
  species: string;
  isDangerous: boolean;
  age?: number; // Opcjonalne pole
  onEscape?: () => void; // Opcjonalna funkcja callback
}

// Komponent funkcyjny z typowanymi props
const DinoCard: React.FC<DinoCardProps> = ({
  name,
  species,
  isDangerous,
  age,
  onEscape
}) => {
  return (
    <div className="dino-card">
      <h2>{name}</h2>
      <p>Gatunek: {species}</p>
      <p>Wiek: {age || 'Nieznany'}</p>
      <div className={isDangerous ? 'danger' : 'safe'}>
        {isDangerous ? 'NIEBEZPIECZNY' : 'Bezpieczny'}
      </div>
      {onEscape && (
        <button onClick={onEscape}>
          Raport o ucieczce
        </button>
      )}
    </div>
  );
};

// Użycie z pełnym typowaniem
const App = () => {
  const handleEscape = () => {
    console.log('ALARM: Dinozaur uciekł!');
  };

  return (
    <DinoCard
      name="Blue"
      species="Velociraptor"
      isDangerous={true}
      age={4}
      onEscape={handleEscape}
    />
  );
};

Brak propa species to błąd kompilacji już w App. Wiele zespołów zamiast React.FC pisze po prostu function DinoCard(props: DinoCardProps), bo od React 18 oba zapisy działają praktycznie tak samo. Przy liczbach lepsze jest ?? niż ||, bo wiek 0 też jest poprawny.

Typowanie React Hooks

Hooki są generyczne. Przy prostych wartościach TypeScript sam wywnioskuje typ, ale dla pustej tablicy albo null podajesz go w nawiasach ostrych:

import { useState, useEffect, useRef, useCallback, useMemo } from 'react';

interface Dinosaur {
  id: number;
  name: string;
  species: string;
  status: 'contained' | 'escaped' | 'feeding';
}

const DinosaurMonitor: React.FC = () => {
  // useState z typem
  const [dinosaurs, setDinosaurs] = useState<Dinosaur[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<Error | null>(null);

  // useRef z typem elementu DOM
  const alertSound = useRef<HTMLAudioElement>(null);

  // useEffect - fetchowanie danych
  useEffect(() => {
    const fetchDinosaurs = async () => {
      setLoading(true);
      try {
        const response = await fetch('/api/dinosaurs');
        const data: Dinosaur[] = await response.json();
        setDinosaurs(data);
      } catch (err) {
        setError(err as Error);
      } finally {
        setLoading(false);
      }
    };

    fetchDinosaurs();
  }, []);

  // useCallback z typowanymi parametrami
  const handleDinoEscape = useCallback((dinoId: number) => {
    setDinosaurs(prev =>
      prev.map(dino =>
        dino.id === dinoId
          ? { ...dino, status: 'escaped' as const }
          : dino
      )
    );

    // Odtwórz alarm
    if (alertSound.current) {
      alertSound.current.play();
    }
  }, []);

  // useMemo z typem zwracanym
  const dangerousDinos = useMemo<Dinosaur[]>(() => {
    return dinosaurs.filter(dino => dino.status === 'escaped');
  }, [dinosaurs]);

  if (loading) return <div>Ładowanie danych monitoringu...</div>;
  if (error) return <div>Błąd: {error.message}</div>;

  return (
    <div>
      <h1>Monitor Dinozaurów</h1>
      <audio ref={alertSound} src="/sounds/alarm.mp3" />

      {dangerousDinos.length > 0 && (
        <div className="alert">
          UWAGA: {dangerousDinos.length} dinozaurów na wolności!
        </div>
      )}

      <div className="dino-grid">
        {dinosaurs.map(dino => (
          <DinoCard
            key={dino.id}
            name={dino.name}
            species={dino.species}
            isDangerous={dino.status === 'escaped'}
            onEscape={() => handleDinoEscape(dino.id)}
          />
        ))}
      </div>
    </div>
  );
};

Bez <Dinosaur[]> pusta tablica miałaby typ never[] i nie dałoby się do niej nic dodać. useRef<HTMLAudioElement>(null) wie, że current to element audio albo null, więc kod sprawdza go przed play(), a as const zachowuje literał 'escaped' zamiast poszerzać go do string.

Custom Hooks z TypeScript

Własny hook zwraca obiekt opisany interfejsem, więc komponent dostaje podpowiedzi do każdej funkcji. Omit<Dinosaur, 'id'> oznacza dinozaura bez id, które nada serwer:

// Custom hook do zarządzania listą dinozaurów
interface UseDinosaursResult {
  dinosaurs: Dinosaur[];
  loading: boolean;
  error: Error | null;
  addDinosaur: (dino: Omit<Dinosaur, 'id'>) => Promise<void>;
  removeDinosaur: (id: number) => Promise<void>;
  updateStatus: (id: number, status: Dinosaur['status']) => void;
}

function useDinosaurs(): UseDinosaursResult {
  const [dinosaurs, setDinosaurs] = useState<Dinosaur[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<Error | null>(null);

  const addDinosaur = useCallback(async (dino: Omit<Dinosaur, 'id'>) => {
    setLoading(true);
    try {
      const response = await fetch('/api/dinosaurs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(dino)
      });
      const newDino: Dinosaur = await response.json();
      setDinosaurs(prev => [...prev, newDino]);
    } catch (err) {
      setError(err as Error);
    } finally {
      setLoading(false);
    }
  }, []);

  const removeDinosaur = useCallback(async (id: number) => {
    setLoading(true);
    try {
      await fetch(`/api/dinosaurs/${id}`, { method: 'DELETE' });
      setDinosaurs(prev => prev.filter(d => d.id !== id));
    } catch (err) {
      setError(err as Error);
    } finally {
      setLoading(false);
    }
  }, []);

  const updateStatus = useCallback((id: number, status: Dinosaur['status']) => {
    setDinosaurs(prev =>
      prev.map(dino =>
        dino.id === id ? { ...dino, status } : dino
      )
    );
  }, []);

  return {
    dinosaurs,
    loading,
    error,
    addDinosaur,
    removeDinosaur,
    updateStatus
  };
}

// Użycie custom hooka
const ParkManager: React.FC = () => {
  const {
    dinosaurs,
    loading,
    error,
    addDinosaur,
    updateStatus
  } = useDinosaurs();

  const handleFeedDino = (id: number) => {
    updateStatus(id, 'feeding');
    setTimeout(() => updateStatus(id, 'contained'), 5000);
  };

  return (
    <div>
      {/* Komponent wykorzystujący hook */}
    </div>
  );
};

Dinosaur['status'] pilnuje, żeby updateStatus przyjmował wyłącznie jeden z trzech statusów.

TypeScript z Node.js/Express - Backend API

Typowanie Express aplikacji

Po stronie serwera typujesz żądania, odpowiedzi i middleware, a kontroler grupuje handlery jednego zasobu:

import express, { Request, Response, NextFunction } from 'express';

// Interfejsy dla modeli danych
interface Dinosaur {
  id: number;
  name: string;
  species: string;
  paddock: number;
  feedingSchedule: string[];
}

interface CreateDinosaurDTO {
  name: string;
  species: string;
  paddock: number;
}

// Rozszerzenie Request o custom pola
interface AuthRequest extends Request {
  user?: {
    id: number;
    role: 'admin' | 'keeper' | 'visitor';
  };
}

// Controller z typowaniem
class DinosaurController {
  // GET /api/dinosaurs
  async getAll(req: Request, res: Response<Dinosaur[]>, next: NextFunction) {
    try {
      const dinosaurs = await this.dinosaurService.findAll();
      res.json(dinosaurs);
    } catch (error) {
      next(error);
    }
  }

  // GET /api/dinosaurs/:id
  async getById(
    req: Request<{ id: string }>,
    res: Response<Dinosaur>,
    next: NextFunction
  ) {
    try {
      const id = parseInt(req.params.id);
      const dinosaur = await this.dinosaurService.findById(id);

      if (!dinosaur) {
        res.status(404).json({ error: 'Dinosaur not found' } as any);
        return;
      }

      res.json(dinosaur);
    } catch (error) {
      next(error);
    }
  }

  // POST /api/dinosaurs
  async create(
    req: Request<{}, {}, CreateDinosaurDTO>,
    res: Response<Dinosaur>,
    next: NextFunction
  ) {
    try {
      const newDino = await this.dinosaurService.create(req.body);
      res.status(201).json(newDino);
    } catch (error) {
      next(error);
    }
  }
}

// Middleware z typowaniem
const authenticateUser = (
  req: AuthRequest,
  res: Response,
  next: NextFunction
): void => {
  const token = req.headers.authorization?.split(' ')[1];

  if (!token) {
    res.status(401).json({ error: 'No token provided' });
    return;
  }

  try {
    const decoded = verifyToken(token);
    req.user = decoded;
    next();
  } catch (error) {
    res.status(401).json({ error: 'Invalid token' });
  }
};

// Routing
const app = express();

app.use(express.json());

const dinoController = new DinosaurController();

app.get('/api/dinosaurs', dinoController.getAll.bind(dinoController));
app.get('/api/dinosaurs/:id', dinoController.getById.bind(dinoController));
app.post('/api/dinosaurs', authenticateUser, dinoController.create.bind(dinoController));

bind(dinoController) jest konieczne, bo metoda przekazana jako callback traci this. Pole this.dinosaurService trzeba jeszcze zadeklarować i wstrzyknąć przez konstruktor, a zamiast interfejsu AuthRequest możesz użyć augmentacji express-serve-static-core z poprzedniej lekcji.

Typowane serwisy i repozytoria

Wzorzec Repository ukrywa bazę danych za generycznym interfejsem Repository<T>, a serwis zawiera logikę biznesową, taką jak walidacja:

// Repository Pattern z TypeScript
interface Repository<T> {
  findAll(): Promise<T[]>;
  findById(id: number): Promise<T | null>;
  create(data: Omit<T, 'id'>): Promise<T>;
  update(id: number, data: Partial<T>): Promise<T>;
  delete(id: number): Promise<void>;
}

class DinosaurRepository implements Repository<Dinosaur> {
  async findAll(): Promise<Dinosaur[]> {
    // Implementacja z bazą danych
    return [];
  }

  async findById(id: number): Promise<Dinosaur | null> {
    // Implementacja
    return null;
  }

  async create(data: Omit<Dinosaur, 'id'>): Promise<Dinosaur> {
    // Implementacja
    return { id: 1, ...data } as Dinosaur;
  }

  async update(id: number, data: Partial<Dinosaur>): Promise<Dinosaur> {
    // Implementacja
    return {} as Dinosaur;
  }

  async delete(id: number): Promise<void> {
    // Implementacja
  }
}

// Service Layer
class DinosaurService {
  constructor(private repository: DinosaurRepository) {}

  async getAllDinosaurs(): Promise<Dinosaur[]> {
    return this.repository.findAll();
  }

  async getDinosaurById(id: number): Promise<Dinosaur> {
    const dino = await this.repository.findById(id);
    if (!dino) {
      throw new Error(`Dinosaur with id ${id} not found`);
    }
    return dino;
  }

  async createDinosaur(data: CreateDinosaurDTO): Promise<Dinosaur> {
    // Walidacja
    this.validateDinosaurData(data);

    // Tworzenie
    return this.repository.create({
      ...data,
      feedingSchedule: this.generateFeedingSchedule(data.species)
    });
  }

  private validateDinosaurData(data: CreateDinosaurDTO): void {
    if (!data.name || data.name.length < 2) {
      throw new Error('Invalid dinosaur name');
    }
    if (data.paddock < 1 || data.paddock > 10) {
      throw new Error('Invalid paddock number');
    }
  }

  private generateFeedingSchedule(species: string): string[] {
    // Logika generowania harmonogramu
    return ['08:00', '14:00', '20:00'];
  }
}

Serwis zależy od konkretnej klasy DinosaurRepository, a zgodnie z zasadą odwrócenia zależności lepiej przyjąć Repository<Dinosaur> i w testach podać repozytorium w pamięci. Partial<T> działa tylko na pierwszym poziomie, więc dla zagnieżdżonych obiektów pisze się rekurencyjny DeepPartial<T>, a wbudowany NonNullable<T> usuwa z typu null i undefined.

TypeScript z Next.js - Full-stack z natywnym wsparciem

Next.js ma wbudowane wsparcie dla TypeScript: wystarczy utworzyć plik .ts lub .tsx, a Next.js sam skonfiguruje kompilator i utworzy tsconfig.json.

Pages i API Routes

W Pages Router strona dostaje typ NextPage<Props>, a funkcja pobierająca dane typ GetServerSideProps<Props>, więc props strony i dane z serwera muszą do siebie pasować:

// pages/dinosaurs/[id].tsx - Dynamic route z typowaniem
import { GetServerSideProps, NextPage } from 'next';

interface DinosaurPageProps {
  dinosaur: Dinosaur;
  lastUpdated: string;
}

// Komponent strony
const DinosaurPage: NextPage<DinosaurPageProps> = ({ dinosaur, lastUpdated }) => {
  return (
    <div>
      <h1>{dinosaur.name}</h1>
      <p>Gatunek: {dinosaur.species}</p>
      <p>Zagroda: {dinosaur.paddock}</p>
      <small>Ostatnia aktualizacja: {lastUpdated}</small>
    </div>
  );
};

// Server-side rendering z typowaniem
export const getServerSideProps: GetServerSideProps<DinosaurPageProps> = async (context) => {
  const { id } = context.params as { id: string };

  try {
    const response = await fetch(`https://api.park.com/dinosaurs/${id}`);
    const dinosaur: Dinosaur = await response.json();

    return {
      props: {
        dinosaur,
        lastUpdated: new Date().toISOString()
      }
    };
  } catch (error) {
    return {
      notFound: true
    };
  }
};

export default DinosaurPage;

Jeśli getServerSideProps zwróci obiekt bez lastUpdated, kompilator zgłosi błąd, zanim strona trafi do zwiedzających.

API Routes w Next.js

Trasa API w Pages Router to funkcja z typami NextApiRequest i NextApiResponse<T>, gdzie T opisuje kształt odpowiedzi:

// pages/api/dinosaurs/[id].ts
import type { NextApiRequest, NextApiResponse } from 'next';

type ResponseData = {
  dinosaur?: Dinosaur;
  error?: string;
};

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  const { id } = req.query;

  if (req.method === 'GET') {
    try {
      const dinosaur = await getDinosaurById(Number(id));
      res.status(200).json({ dinosaur });
    } catch (error) {
      res.status(404).json({ error: 'Dinosaur not found' });
    }
  } else if (req.method === 'PUT') {
    try {
      const updatedDino = await updateDinosaur(Number(id), req.body);
      res.status(200).json({ dinosaur: updatedDino });
    } catch (error) {
      res.status(400).json({ error: 'Update failed' });
    }
  } else {
    res.status(405).json({ error: 'Method not allowed' });
  }
}

req.query.id ma typ string | string[] | undefined, dlatego kod zamienia go na liczbę, a nieobsługiwana metoda dostaje status 405.

App Router (Next.js 13+) z Server Components

W App Router strona jest domyślnie Server Component, który może być funkcją async i pobierać dane bezpośrednio. Interaktywne fragmenty wydzielasz do Client Components:

// app/dinosaurs/[id]/page.tsx
// Od Next.js 15 params i searchParams to obiekty Promise
interface PageProps {
  params: Promise<{ id: string }>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}

// Server Component
export default async function DinosaurDetailPage({ params }: PageProps) {
  const { id } = await params;
  const dinosaur = await getDinosaurById(id);

  return (
    <div>
      <h1>{dinosaur.name}</h1>
      <DinosaurDetails dino={dinosaur} />
    </div>
  );
}

// Client Component - osobny plik, np. app/dinosaurs/[id]/DinosaurDetails.tsx,
// bo dyrektywa 'use client' musi stać na samym początku pliku
'use client';

interface DinosaurDetailsProps {
  dino: Dinosaur;
}

export function DinosaurDetails({ dino }: DinosaurDetailsProps) {
  const [isFavorite, setIsFavorite] = useState(false);

  return (
    <div>
      <button onClick={() => setIsFavorite(!isFavorite)}>
        {isFavorite ? '★' : '☆'} Ulubiony
      </button>
      {/* Reszta komponentu */}
    </div>
  );
}

Od Next.js 15 params jest obiektem Promise, więc najpierw go oczekujesz, a w wersjach 13 i 14 był zwykłym obiektem. Dyrektywa 'use client' musi stać na początku osobnego pliku, dlatego DinosaurDetails mieszka we własnym module.

Wzorce typowania w frameworkach

Generic Components

Komponent generyczny działa dla dowolnego typu elementów, a TypeScript pilnuje, żeby renderItem i keyExtractor pasowały do przekazanej tablicy:

// Uniwersalny komponent listy z typowaniem
interface ListProps<T> {
  items: T[];
  renderItem: (item: T, index: number) => React.ReactNode;
  keyExtractor: (item: T) => string | number;
  emptyMessage?: string;
}

function List<T>({ items, renderItem, keyExtractor, emptyMessage }: ListProps<T>) {
  if (items.length === 0) {
    return <div>{emptyMessage || 'Brak elementów'}</div>;
  }

  return (
    <ul>
      {items.map((item, index) => (
        <li key={keyExtractor(item)}>
          {renderItem(item, index)}
        </li>
      ))}
    </ul>
  );
}

// Użycie
const DinosaurList = () => {
  const dinosaurs: Dinosaur[] = [
    { id: 1, name: 'Rex', species: 'T-Rex', paddock: 1, feedingSchedule: [] },
    { id: 2, name: 'Blue', species: 'Velociraptor', paddock: 3, feedingSchedule: [] }
  ];

  return (
    <List<Dinosaur>
      items={dinosaurs}
      keyExtractor={(dino) => dino.id}
      renderItem={(dino) => (
        <div>
          <strong>{dino.name}</strong> - {dino.species}
        </div>
      )}
      emptyMessage="Brak dinozaurów w systemie"
    />
  );
};

Zapis List<Dinosaur> w JSX jawnie podaje typ, choć TypeScript wywnioskowałby go z items, a ten sam komponent wyświetli też listę wybiegów.

Form handling z TypeScript

Biblioteka react-hook-form przyjmuje typ danych formularza, więc register akceptuje tylko istniejące nazwy pól:

import { useForm, SubmitHandler } from 'react-hook-form';

interface DinosaurFormData {
  name: string;
  species: string;
  paddock: number;
  isDangerous: boolean;
  feedingTimes: string[];
}

const DinosaurForm: React.FC = () => {
  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm<DinosaurFormData>();

  const onSubmit: SubmitHandler<DinosaurFormData> = async (data) => {
    try {
      const response = await fetch('/api/dinosaurs', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
      });

      if (response.ok) {
        alert('Dinozaur dodany!');
      }
    } catch (error) {
      console.error('Błąd podczas dodawania:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input
        {...register('name', { required: 'Nazwa jest wymagana' })}
        placeholder="Nazwa dinozaura"
      />
      {errors.name && <span>{errors.name.message}</span>}

      <input
        {...register('species', { required: true })}
        placeholder="Gatunek"
      />

      <input
        type="number"
        {...register('paddock', {
          required: true,
          min: 1,
          max: 10,
          valueAsNumber: true // bez tego wartość z pola number jest napisem
        })}
        placeholder="Numer zagrody"
      />

      <label>
        <input type="checkbox" {...register('isDangerous')} />
        Niebezpieczny gatunek
      </label>

      <button type="submit">Dodaj dinozaura</button>
    </form>
  );
};

Literówka w nazwie pola to błąd kompilacji. Pole type="number" zwraca w przeglądarce napis, dlatego opcja valueAsNumber zamienia go na liczbę zgodną z typem paddock: number.

Podsumowanie

"Widzisz?" uśmiecha się Dr. Rex. "TypeScript świetnie integruje się z popularnymi frameworkami."

React

  • Silne typowanie komponentów przez React.FC<Props>
  • Typowane hooki (useState<T>, useRef<HTMLElement>)
  • Custom hooks z pełnym type safety
  • Generic components dla reużywalności

Node.js/Express

  • Typowanie Request, Response, NextFunction
  • Repository i Service patterns z interfejsami
  • Middleware z custom Request types
  • DTO (Data Transfer Objects) opisujące dane wejściowe

Next.js

  • Natywne wsparcie TypeScript bez ręcznej konfiguracji
  • Typowane getServerSideProps i getStaticProps
  • API Routes z typowaniem
  • Server i Client Components w App Router

Kluczowe korzyści to łapanie błędów już podczas pisania kodu, autouzupełnianie (IntelliSense), refaktoryzacja bez obaw, samodokumentujący się kod i łatwiejsza współpraca w zespole. Nowy projekt zaczynaj od razu w TypeScript z trybem strict bo dopisywanie typów do gotowej aplikacji kosztuje więcej. W kolejnej lekcji połączysz wiedzę z całego modułu w projekcie końcowym: systemie diagnostycznym parku.

"TypeScript to zabezpieczenie systemów parku, które na początku wymaga trochę pracy, ale w dłuższej perspektywie oszczędza mnóstwo problemów" - kończy Dr. Rex.

Kod do tej lekcji: index.js
// Profiling pamięci - znajdź i napraw memory leaks
console.log("Park Jurajski - Laboratorium Profilingu Pamięci");
console.log("Znajdź i napraw memory leaks w kodzie!\n");

// ====================================
// ZADANIE: Poniższy kod ma kilka memory leaks.
// Napraw je stosując dobre praktyki.
// ====================================

// LEAK 1: Event listeners bez cleanup
// Napraw: Dodaj metodę destroy() z removeEventListener
class DinosaurTracker {
  constructor(name) {
    this.name = name;
    this.positions = [];
    this.handler = this.onPositionUpdate.bind(this);
    // Symulacja addEventListener
    console.log(`Tracker dla ${name} - listener dodany`);
  }

  onPositionUpdate(position) {
    this.positions.push(position);
  }

  // TODO: Dodaj metodę destroy() która usunie event listener
  destroy() {
    // Rozwiązanie: usunięcie listenera
    // removeEventListener('position', this.handler);
    this.positions = [];
    this.handler = null;
    console.log(`Tracker dla ${this.name} - listener usunięty, pamięć zwolniona`);
  }
}

// LEAK 2: Rosnąca tablica bez limitu
// Napraw: Ogranicz rozmiar tablicy
class AlertSystem {
  constructor() {
    this.alerts = [];
    this.maxAlerts = 100; // TODO: Ustaw limit
  }

  addAlert(message) {
    // TODO: Sprawdź limit i usuń najstarsze alerty
    if (this.alerts.length >= this.maxAlerts) {
      this.alerts.shift(); // Usuń najstarszy
    }
    this.alerts.push({
      message,
      timestamp: Date.now()
    });
  }

  getAlertCount() {
    return this.alerts.length;
  }
}

// LEAK 3: Zapomniane timery
// Napraw: Dodaj cleanup dla timerów
class HealthMonitor {
  constructor() {
    this.timers = [];
    this.data = [];
  }

  startMonitoring(dinoName, intervalMs) {
    const timer = setInterval(() => {
      this.data.push({
        dino: dinoName,
        health: Math.random() * 100,
        time: Date.now()
      });
    }, intervalMs);

    this.timers.push(timer);
    console.log(`Monitoring ${dinoName} started`);
  }

  // TODO: Dodaj metodę stopAll() czyszczącą timery
  stopAll() {
    this.timers.forEach(timer => clearInterval(timer));
    this.timers = [];
    this.data = [];
    console.log("Wszystkie monitory zatrzymane, timery wyczyszczone");
  }
}

// LEAK 4: Circular references
// Napraw: Użyj WeakRef lub WeakMap
class Enclosure {
  constructor(name) {
    this.name = name;
    this.dinosaurs = [];
  }

  addDinosaur(dino) {
    this.dinosaurs.push(dino);
    // Circular reference: dino -> enclosure -> dino
    dino.enclosure = this;
  }
}

// Rozwiązanie z WeakRef
class EnclosureFixed {
  constructor(name) {
    this.name = name;
    this.dinosaurs = new Set();
  }

  addDinosaur(dino) {
    this.dinosaurs.add(dino);
    // WeakRef nie blokuje garbage collection
    dino.enclosureRef = new WeakRef(this);
  }

  removeDinosaur(dino) {
    this.dinosaurs.delete(dino);
    dino.enclosureRef = null;
  }
}

// ====================================
// TESTY
// ====================================
console.log("=== Test naprawionych leaków ===\n");

// Test 1: Tracker z cleanup
const tracker = new DinosaurTracker("T-Rex");
tracker.onPositionUpdate({ x: 10, y: 20 });
tracker.onPositionUpdate({ x: 15, y: 25 });
console.log("Pozycje przed destroy:", tracker.positions.length);
tracker.destroy();
console.log("Pozycje po destroy:", tracker.positions.length);

// Test 2: Alert system z limitem
console.log("\n--- Alert System ---");
const alertSys = new AlertSystem();
for (let i = 0; i < 150; i++) {
  alertSys.addAlert(`Alert #${i}`);
}
console.log(`Alerty po 150 dodaniach (limit 100): ${alertSys.getAlertCount()}`);

// Test 3: Health monitor z cleanup
console.log("\n--- Health Monitor ---");
const healthMon = new HealthMonitor();
healthMon.startMonitoring("Velociraptor", 1000);
healthMon.startMonitoring("Stegosaurus", 2000);
console.log("Aktywne timery:", healthMon.timers.length);
healthMon.stopAll();
console.log("Timery po stopAll:", healthMon.timers.length);

// Test 4: WeakRef rozwiązanie
console.log("\n--- Enclosure z WeakRef ---");
const enclosure = new EnclosureFixed("Paddock A");
let dino = { name: "Raptor", species: "Velociraptor" };
enclosure.addDinosaur(dino);
console.log("Dinozaur w zagrodzie:", enclosure.dinosaurs.size);

const encRef = dino.enclosureRef.deref();
console.log("Enclosure przez WeakRef:", encRef ? encRef.name : "GC collected");

console.log("\nWszystkie memory leaks naprawione!");
console.log("Dobre praktyki:");
console.log("1. Zawsze usuwaj event listeners (destroy/cleanup)");
console.log("2. Ogranicz rozmiar tablic (ring buffer / maxSize)");
console.log("3. Czyść timery (clearInterval/clearTimeout)");
console.log("4. Użyj WeakRef/WeakMap dla circular references");

Hasła z dokumentacji w tej lekcji

Widzisz błąd w tej lekcji?

Zadania praktyczne w grze

  • Edytor kodu

    Zaimplementuj DeepPartial i NonNullable.

  1. Zadanie z kodemPowtórzenie: Record i własne utility types

Przydatne artykuły