TSTypeScript

TypeScript: Types – code examples

Contents

Interface, Type Alias & Intersection

Types#interface#type#readonly#intersection
Use case: Describe the shape of data, e.g. API responses, forms or database rows.
interface Nutzer {
  readonly id: number;
  name: string;
  email?: string;
}
type Rolle = "admin" | "editor" | "gast";
type Admin = Nutzer & { rolle: Rolle };

const ada: Nutzer = { id: 1, name: "Ada" };
const chef: Admin = { id: 2, name: "Grace", rolle: "admin" };
function zeigen(n: Nutzer): string {
  return n.name + (n.email ? " <" + n.email + ">" : "");
}
console.log(zeigen(ada), chef.rolle);

? makes fields optional, readonly forbids changing them later. With & you combine types; Admin can still be passed to zeigen (structural typing).

Narrowing union types

Types#union#narrowing#typeof
Use case: Process values that can have several types (inputs, API fields).
function formatiere(wert: string | number | null): string {
  if (wert === null) return "–";
  if (typeof wert === "number") return wert.toFixed(2);
  return wert.toUpperCase();
}

console.log(formatiere(3.14159));
console.log(formatiere("hallo"));
console.log(formatiere(null));

After each check the compiler knows which type is left (narrowing) – toFixed is only allowed on number.

Discriminated union with exhaustiveness check

Types#union#switch#never#discriminated
Use case: Model states, e.g. loading states, shapes or message types.
type Form =
  | { art: "kreis"; radius: number }
  | { art: "rechteck"; breite: 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;
    default: {
      const unmoeglich: never = f;
      return unmoeglich;
    }
  }
}
console.log(flaeche({ art: "rechteck", breite: 3, hoehe: 4 }));

The field art distinguishes the variants. If a new shape is added and forgotten here, the compiler reports an error at the never branch.

as const and derived types

Types#as const#literal#enum#keyof
Use case: Define constant lists (status, colors, roles) once and reuse them as a type.
const FARBEN = ["rot", "gruen", "blau"] as const;
type Farbe = (typeof FARBEN)[number];

const STATUS = { OFFEN: "offen", FERTIG: "fertig" } as const;
type Status = (typeof STATUS)[keyof typeof STATUS];

function setze(f: Farbe, s: Status): void {
  console.log(f, s);
}
setze("rot", STATUS.FERTIG);
// setze("lila", "offen");   // compiler error
console.log(FARBEN.length, Object.values(STATUS));

as const turns values into literal types and makes them read-only. That way the same constant serves as a runtime list and as a type – a good alternative to enum.

Custom type guard

Types#type guard#predicate#in
Use case: Safely distinguish different object types, e.g. events or response variants.
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" }));
console.log(laut({ miau: () => "Meow" }));

The return type tier is Katze tells the compiler that tier is a Katze in the positive case – in the other case Hund remains.

Named tuples

Types#tuple#destructuring#return
Use case: Multiple return values in a fixed order, e.g. coordinates or [value, error].
type Punkt = [x: number, y: number];
const p: Punkt = [3, 4];
const [x, y] = p;
console.log(Math.hypot(x, y));

function minMax(zahlen: number[]): [min: number, max: number] {
  return [Math.min(...zahlen), Math.max(...zahlen)];
}
const [kleinste, groesste] = minMax([4, 9, 2]);
console.log(kleinste, groesste);

Tuples fix the length and the type of each position; the names (x:, min:) document the meaning and show up in the editor.