Kurs JavaScript i TypeScript · Moduł 7: Zaawansowany TypeScript

Type narrowing i type guards

9 min czytania ·
W tej lekcji7

"W Parku Jurajskim nie wystarczy wiedzieć, że masz przed sobą dinozaura," mówi Robert Muldoon, główny łowczy parku. "Musisz dokładnie wiedzieć, CZY to drapieżnik, CZY roślinożerca, CZY lata, CZY pływa. Od tego zależy, jaki protokół bezpieczeństwa uruchomisz. Jedno złe założenie i masz katastrofę."

Podobnie działa type narrowing w TypeScript - to proces zawężania szerokiego typu do bardziej konkretnego. Gdy zmienna ma typ string | number, TypeScript nie wie, czy to tekst czy liczba. Dzięki type guards możemy "zawęzić" typ, by kompilator wiedział dokładnie, z czym ma do czynienia. To fundamentalna technika pisania bezpiecznego kodu TypeScript.

Operator typeof jako type guard

Najprostszym type guardem jest typeof - operator JavaScript, który TypeScript rozumie i wykorzystuje do zawężania typów. Gdy sprawdzisz typ zmiennej za pomocą typeof, kompilator automatycznie wie, jaki typ ma zmienna wewnątrz bloku if.

// Funkcja przyjmująca różne typy danych dinozaura
function formatDinosaurData(value: string | number | boolean): string {
  if (typeof value === "string") {
    // TypeScript wie, że tutaj value jest typu string
    return value.toUpperCase();
  }
  if (typeof value === "number") {
    // TypeScript wie, że tutaj value jest typu number
    return value.toFixed(2) + " kg";
  }
  // TypeScript wie, że tutaj value jest typu boolean
  return value ? "Aktywny" : "Nieaktywny";
}

console.log(formatDinosaurData("Tyrannosaurus Rex")); // "TYRANNOSAURUS REX"
console.log(formatDinosaurData(7500));                 // "7500.00 kg"
console.log(formatDinosaurData(true));                 // "Aktywny"

W powyższym przykładzie TypeScript automatycznie zawęża typ value w każdym bloku if. Po sprawdzeniu typeof value === "string" kompilator wie, że wewnątrz tego bloku value jest stringiem, więc możesz bezpiecznie wywoływać .toUpperCase(). To działa z typami "string", "number", "boolean", "bigint", "symbol", "undefined", "object" i "function".

Operator instanceof

Gdy pracujesz z klasami, instanceof pozwala sprawdzić, czy obiekt jest instancją konkretnej klasy. TypeScript automatycznie zawęża typ po takim sprawdzeniu.

class Carnivore {
  name: string;
  biteForce: number;

  constructor(name: string, biteForce: number) {
    this.name = name;
    this.biteForce = biteForce;
  }

  hunt(): string {
    return `${this.name} poluje z siłą ugryzienia ${this.biteForce}N!`;
  }
}

class Herbivore {
  name: string;
  favoriteFood: string;

  constructor(name: string, favoriteFood: string) {
    this.name = name;
    this.favoriteFood = favoriteFood;
  }

  graze(): string {
    return `${this.name} spokojnie zjada ${this.favoriteFood}`;
  }
}

// Funkcja obsługująca oba typy dinozaurów
function handleDinosaur(dino: Carnivore | Herbivore): string {
  if (dino instanceof Carnivore) {
    // TypeScript wie, że tutaj dino jest Carnivore
    return dino.hunt(); // Mamy dostęp do hunt() i biteForce
  }
  // TypeScript wie, że tutaj dino jest Herbivore
  return dino.graze(); // Mamy dostęp do graze() i favoriteFood
}

const rex = new Carnivore("T-Rex", 12800);
const trike = new Herbivore("Triceratops", "Paprocie");

console.log(handleDinosaur(rex));   // "T-Rex poluje z siłą ugryzienia 12800N!"
console.log(handleDinosaur(trike)); // "Triceratops spokojnie zjada Paprocie"

Operator in

Operator in sprawdza, czy obiekt posiada daną właściwość. TypeScript wykorzystuje to do zawężania typów w union types.

interface FlyingDinosaur {
  name: string;
  maxAltitude: number;
  wingspan: number;
}

interface SwimmingDinosaur {
  name: string;
  maxDepth: number;
  swimSpeed: number;
}

interface LandDinosaur {
  name: string;
  runSpeed: number;
  weight: number;
}

type Dinosaur = FlyingDinosaur | SwimmingDinosaur | LandDinosaur;

function describeDinosaur(dino: Dinosaur): string {
  if ("maxAltitude" in dino) {
    // TypeScript wie, że to FlyingDinosaur
    return `${dino.name} lata na wysokości do ${dino.maxAltitude}m, rozpiętość skrzydeł: ${dino.wingspan}m`;
  }
  if ("maxDepth" in dino) {
    // TypeScript wie, że to SwimmingDinosaur
    return `${dino.name} nurkuje do ${dino.maxDepth}m, prędkość: ${dino.swimSpeed} km/h`;
  }
  // TypeScript wie, że to LandDinosaur
  return `${dino.name} biega z prędkością ${dino.runSpeed} km/h, waży ${dino.weight} kg`;
}

const pteranodon: FlyingDinosaur = { name: "Pteranodon", maxAltitude: 500, wingspan: 7 };
const mosasaurus: SwimmingDinosaur = { name: "Mosasaurus", maxDepth: 200, swimSpeed: 48 };
const velociraptor: LandDinosaur = { name: "Velociraptor", runSpeed: 64, weight: 15 };

console.log(describeDinosaur(pteranodon));
console.log(describeDinosaur(mosasaurus));
console.log(describeDinosaur(velociraptor));

Operator in jest szczególnie przydatny, gdy pracujesz z interfejsami (nie klasami), bo instanceof działa tylko z klasami, natomiast in sprawdza po prostu obecność właściwości.

Custom type guard functions (słowo kluczowe is)

Możesz tworzyć własne funkcje typu guard, które zwracają specjalny typ parameterName is Type. Dzięki temu TypeScript rozumie, że po pozytywnym sprawdzeniu zmienna ma konkretny typ.

interface DinoEgg {
  species: string;
  weight: number;
  incubationDays: number;
}

interface HatchedDino {
  species: string;
  weight: number;
  age: number;
  enclosureId: string;
}

// Custom type guard - funkcja zwraca "specimen is HatchedDino"
function isHatched(specimen: DinoEgg | HatchedDino): specimen is HatchedDino {
  return "age" in specimen && "enclosureId" in specimen;
}

function processSpecimen(specimen: DinoEgg | HatchedDino): string {
  if (isHatched(specimen)) {
    // TypeScript wie, że tutaj specimen jest HatchedDino
    return `${specimen.species} - wiek: ${specimen.age} dni, zagroda: ${specimen.enclosureId}`;
  }
  // TypeScript wie, że tutaj specimen jest DinoEgg
  return `Jajo ${specimen.species} - inkubacja: ${specimen.incubationDays} dni`;
}

// Bardziej zaawansowany type guard z walidacją
function isCarnivoreData(data: unknown): data is { species: string; biteForce: number; diet: "carnivore" } {
  return (
    typeof data === "object" &&
    data !== null &&
    "species" in data &&
    "biteForce" in data &&
    "diet" in data &&
    (data as any).diet === "carnivore"
  );
}

// Użycie z nieznanym źródłem danych (np. API)
function processParkData(rawData: unknown): string {
  if (isCarnivoreData(rawData)) {
    // TypeScript wie, że rawData ma pola species, biteForce, diet
    return `Drapieżnik: ${rawData.species}, siła: ${rawData.biteForce}N`;
  }
  return "Nieznany typ danych";
}

console.log(processParkData({ species: "T-Rex", biteForce: 12800, diet: "carnivore" }));
console.log(processParkData({ name: "Triceratops" }));

Custom type guards są szczególnie przydatne, gdy:

  1. Logika sprawdzania jest złożona i chcesz ją wyekstrahować do osobnej funkcji
  2. Pracujesz z danymi z zewnętrznych źródeł (API, pliki JSON), których typ to unknown
  3. Chcesz stworzyć reużywalne narzędzia walidacji

Discriminated unions i exhaustive checks

Discriminated unions to wzorzec, w którym każdy typ w unii ma wspólne pole "dyskryminujące" (tag), które jednoznacznie identyfikuje typ. TypeScript doskonale radzi sobie z zawężaniem typów na podstawie tego pola.

// Każdy typ ma pole "kind" jako dyskryminator
interface SecurityAlert {
  kind: "security";
  zone: string;
  threatLevel: number;
  dinosaurId: string;
}

interface MedicalAlert {
  kind: "medical";
  dinosaurId: string;
  symptoms: string[];
  veterinarianRequired: boolean;
}

interface SystemAlert {
  kind: "system";
  component: string;
  errorCode: number;
  message: string;
}

type ParkAlert = SecurityAlert | MedicalAlert | SystemAlert;

function handleAlert(alert: ParkAlert): string {
  switch (alert.kind) {
    case "security":
      // TypeScript wie, że to SecurityAlert
      return `ALARM BEZPIECZEŃSTWA! Strefa: ${alert.zone}, Zagrożenie: ${alert.threatLevel}/10, Dinozaur: ${alert.dinosaurId}`;
    case "medical":
      // TypeScript wie, że to MedicalAlert
      return `ALERT MEDYCZNY! Dinozaur: ${alert.dinosaurId}, Objawy: ${alert.symptoms.join(", ")}`;
    case "system":
      // TypeScript wie, że to SystemAlert
      return `AWARIA SYSTEMU! Komponent: ${alert.component}, Kod: ${alert.errorCode}`;
  }
}

Exhaustive check z typem never

Typ never w TypeScript oznacza "wartość, która nigdy nie wystąpi". Możemy go użyć do sprawdzenia, czy obsłużyliśmy WSZYSTKIE warianty discriminated union. Jeśli dodamy nowy wariant i zapomnimy go obsłużyć, TypeScript zgłosi błąd kompilacji.

// Exhaustive check - TypeScript ostrzeże nas, jeśli pominiemy jakikolwiek wariant
function handleAlertExhaustive(alert: ParkAlert): string {
  switch (alert.kind) {
    case "security":
      return `Bezpieczeństwo: ${alert.zone}`;
    case "medical":
      return `Medyczny: ${alert.dinosaurId}`;
    case "system":
      return `System: ${alert.component}`;
    default:
      // Jeśli dodamy nowy typ alertu i zapomnimy go obsłużyć,
      // TypeScript zgłosi błąd, bo alert nie będzie typu never
      const exhaustiveCheck: never = alert;
      return exhaustiveCheck;
  }
}

// Praktyczny helper do exhaustive check
function assertNever(value: never, message: string = "Nieobsłużony wariant"): never {
  throw new Error(`${message}: ${JSON.stringify(value)}`);
}

Exhaustive check to potężna technika - gdy dodasz np. WeatherAlert do unii ParkAlert, kompilator NATYCHMIAST wskaże wszystkie miejsca w kodzie, gdzie brakuje obsługi nowego wariantu. To jak system wczesnego ostrzegania w Parku Jurajskim - nie pozwala na przeoczenie żadnego zagrożenia.

Łączenie type guards - praktyczny przykład

Poniżej bardziej rozbudowany przykład łączący różne techniki type narrowing w jednym systemie:

// System klasyfikacji próbek laboratoryjnych
type SampleStatus = "collected" | "analyzing" | "completed" | "contaminated";

interface BaseSample {
  id: string;
  collectedAt: Date;
  status: SampleStatus;
}

interface DNASample extends BaseSample {
  type: "dna";
  species: string;
  purity: number;
  sequenceLength: number;
}

interface BloodSample extends BaseSample {
  type: "blood";
  species: string;
  volumeMl: number;
  pH: number;
}

interface FossilSample extends BaseSample {
  type: "fossil";
  era: string;
  estimatedAge: number;
}

type LabSample = DNASample | BloodSample | FossilSample;

// Custom type guard
function isDNASample(sample: LabSample): sample is DNASample {
  return sample.type === "dna";
}

// Sprawdzenie statusu za pomocą typeof i custom guard
function canProcess(sample: LabSample): boolean {
  return sample.status === "collected" || sample.status === "analyzing";
}

// Główna funkcja przetwarzania - łączy różne techniki
function processLabSample(sample: LabSample): string {
  // Discriminated union narrowing
  switch (sample.type) {
    case "dna":
      if (sample.purity < 50) {
        return `Próbka DNA ${sample.id}: zbyt niska czystość (${sample.purity}%)`;
      }
      return `Analiza DNA ${sample.species}: ${sample.sequenceLength} par zasad, czystość ${sample.purity}%`;

    case "blood":
      const phStatus = sample.pH >= 7.0 && sample.pH <= 7.6 ? "norma" : "POZA NORMĄ";
      return `Analiza krwi ${sample.species}: ${sample.volumeMl}ml, pH ${sample.pH} (${phStatus})`;

    case "fossil":
      return `Skamieniałość z ery ${sample.era}: szacowany wiek ${sample.estimatedAge} mln lat`;

    default:
      const _exhaustive: never = sample;
      return _exhaustive;
  }
}

// Test
const dnaSample: DNASample = {
  id: "DNA-042", type: "dna", collectedAt: new Date(),
  status: "collected", species: "Velociraptor", purity: 87, sequenceLength: 75000000
};

const bloodSample: BloodSample = {
  id: "BLD-015", type: "blood", collectedAt: new Date(),
  status: "analyzing", species: "Triceratops", volumeMl: 120, pH: 7.2
};

const fossilSample: FossilSample = {
  id: "FOS-003", type: "fossil", collectedAt: new Date(),
  status: "completed", era: "Kreda", estimatedAge: 68
};

console.log(processLabSample(dnaSample));
console.log(processLabSample(bloodSample));
console.log(processLabSample(fossilSample));

Podsumowanie

Type narrowing i type guards to fundamentalne narzędzia TypeScript, które pozwalają pisać bezpieczny kod przy jednoczesnym zachowaniu elastyczności union types:

  1. typeof - zawęża typy prymitywne (string, number, boolean)
  2. instanceof - zawęża typy klas
  3. in - zawęża typy na podstawie obecności właściwości w obiekcie
  4. Custom type guards (is) - definiujesz własne funkcje sprawdzające typ
  5. Discriminated unions - wspólne pole "tag" jednoznacznie identyfikuje wariant
  6. Exhaustive check z never - kompilator pilnuje, że obsłużyłeś wszystkie warianty

Jak mówi Robert Muldoon: "Identyfikacja gatunku to pierwszy krok protokołu bezpieczeństwa. Podobnie type narrowing to pierwszy krok do bezpiecznego kodu - nigdy nie zakładaj, z czym masz do czynienia. Sprawdź, zawęź typ i działaj pewnie."

Kod do tej lekcji: index.ts
// Type narrowing i type guards - Park Jurajski
console.log("=== TYPE NARROWING I TYPE GUARDS ===\n");

// ===========================================
// 1. typeof - zawezanie typow prymitywnych
// ===========================================

function formatDinoData(value: string | number | boolean): string {
  if (typeof value === "string") {
    return value.toUpperCase();
  }
  if (typeof value === "number") {
    return value.toFixed(2) + " kg";
  }
  return value ? "Aktywny" : "Nieaktywny";
}

console.log("--- typeof ---");
console.log(formatDinoData("Tyrannosaurus Rex"));
console.log(formatDinoData(7500));
console.log(formatDinoData(true));

// ===========================================
// 2. instanceof - zawezanie klas
// ===========================================

class Carnivore {
  constructor(public name: string, public biteForce: number) {}
  hunt(): string { return `${this.name} poluje z sila ${this.biteForce}N!`; }
}

class Herbivore {
  constructor(public name: string, public food: string) {}
  graze(): string { return `${this.name} zjada ${this.food}`; }
}

function handleDino(dino: Carnivore | Herbivore): string {
  if (dino instanceof Carnivore) {
    return dino.hunt();
  }
  return dino.graze();
}

console.log("\n--- instanceof ---");
console.log(handleDino(new Carnivore("T-Rex", 12800)));
console.log(handleDino(new Herbivore("Triceratops", "paprocie")));

// ===========================================
// 3. in - sprawdzanie wlasciwosci
// ===========================================

interface FlyingDino { name: string; maxAltitude: number; }
interface SwimmingDino { name: string; maxDepth: number; }
interface LandDino { name: string; runSpeed: number; }

type AnyDino = FlyingDino | SwimmingDino | LandDino;

function describeDino(dino: AnyDino): string {
  if ("maxAltitude" in dino) return `${dino.name} lata do ${dino.maxAltitude}m`;
  if ("maxDepth" in dino) return `${dino.name} nurkuje do ${dino.maxDepth}m`;
  return `${dino.name} biega ${dino.runSpeed} km/h`;
}

console.log("\n--- in operator ---");
console.log(describeDino({ name: "Pteranodon", maxAltitude: 500 }));
console.log(describeDino({ name: "Mosasaurus", maxDepth: 200 }));
console.log(describeDino({ name: "Velociraptor", runSpeed: 64 }));

// ===========================================
// 4. Custom type guard (is)
// ===========================================

interface DinoEgg { species: string; incubationDays: number; }
interface HatchedDino { species: string; age: number; enclosureId: string; }

function isHatched(s: DinoEgg | HatchedDino): s is HatchedDino {
  return "age" in s && "enclosureId" in s;
}

console.log("\n--- Custom type guard ---");
const egg: DinoEgg = { species: "Raptor", incubationDays: 45 };
const baby: HatchedDino = { species: "Raptor", age: 10, enclosureId: "E-01" };
console.log("Egg hatched?", isHatched(egg));
console.log("Baby hatched?", isHatched(baby));

// ===========================================
// 5. Discriminated union + exhaustive check
// ===========================================

interface SecurityAlert { kind: "security"; zone: string; level: number; }
interface MedicalAlert { kind: "medical"; dinoId: string; symptoms: string[]; }
interface SystemAlert { kind: "system"; component: string; errorCode: number; }

type ParkAlert = SecurityAlert | MedicalAlert | SystemAlert;

function handleAlert(alert: ParkAlert): string {
  switch (alert.kind) {
    case "security": return `BEZPIECZENSTWO: strefa ${alert.zone}, poziom ${alert.level}`;
    case "medical": return `MEDYCZNY: dino ${alert.dinoId}, objawy: ${alert.symptoms.join(", ")}`;
    case "system": return `SYSTEM: ${alert.component}, kod ${alert.errorCode}`;
    default:
      const _never: never = alert;
      return _never;
  }
}

console.log("\n--- Discriminated union ---");
console.log(handleAlert({ kind: "security", zone: "A", level: 9 }));
console.log(handleAlert({ kind: "medical", dinoId: "D-01", symptoms: ["goraczka"] }));
console.log(handleAlert({ kind: "system", component: "Ogrodzenie", errorCode: 500 }));

console.log("\nType narrowing = bezpieczny kod z union types!");

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. 1. Który operator pozwala na zawężenie typu prymitywnego (np. string | number) w TypeScript?

Zadania praktyczne w grze

  • Edytor kodu

    Użyj typeof, instanceof i operatora in do zawężania typów w systemie Parku Jurajskiego

  • Klikanie w kolejności

    Ułóż elementy custom type guard function:

  1. PytanieOperator typeof jako type guard
  2. Zadanie z kodemType narrowing - praktyka
  3. Kliknij w kolejnościSortowanie: Custom type guard

Przydatne artykuły