TSTypeScript
IntermediateLesson 6 of 15

Narrowing, Type Guards & Discriminated Unions – TypeScript

Narrowing types in code and letting the compiler check all cases.

TypeScript follows the control flow and narrows types automatically: through typeof, instanceof, in, equality checks and truthiness.

function laenge(x: string | string[] | undefined): number {
  if (!x) return 0;                        // undefined and "" excluded
  if (Array.isArray(x)) return x.length;   // here: string[]
  return x.length;                         // here: string
}

function alsDatum(wert: string | Date): Date {
  return wert instanceof Date ? wert : new Date(wert);
}
console.log(laenge(undefined), laenge(["a", "b"]), laenge("Hello"));

The most important technique for data models: discriminated unions. Each variant has a common literal field (the "discriminator") by which TypeScript tells them apart:

type Form =
  | { art: "kreis"; radius: number }
  | { art: "rechteck"; breite: number; hoehe: number }
  | { art: "dreieck"; basis: number; hoehe: number };

function flaeche(f: Form): number {
  switch (f.art) {
    case "kreis":
      return Math.PI * f.radius ** 2;
    case "rechteck":
      return f.breite * f.hoehe;
    case "dreieck":
      return (f.basis * f.hoehe) / 2;
    default: {
      const unmoeglich: never = f;    // error as soon as a variant is missing
      return unmoeglich;
    }
  }
}
console.log(flaeche({ art: "rechteck", breite: 3, hoehe: 4 }));

For your own checks you write type predicates (x is Type). They are the key to safely narrowing unknown values (e.g. from JSON). Assertion functions (asserts) throw an error if the type is wrong:

interface Katze { miau(): string }
interface Hund { belle(): string }

function istKatze(tier: Katze | Hund): tier is Katze {
  return "miau" in tier;
}
function laut(tier: Katze | Hund): string {
  return istKatze(tier) ? tier.miau() : tier.belle();
}
console.log(laut({ belle: () => "Woof" }));

function stelleSicher(bedingung: unknown, text: string): asserts bedingung {
  if (!bedingung) throw new Error(text);
}
function zeige(name: string | undefined) {
  stelleSicher(name !== undefined, "Name is missing");
  console.log(name.toUpperCase());   // from here on: string
}
TipCheck for exhaustiveness with the never trick: if you later add a new variant to the union, the compiler reports every switch that does not handle it.