TSTypeScript
AdvancedLesson 14 of 15

Advanced Patterns: satisfies, Brands & Overloads – TypeScript

Proven techniques for safe and expressive APIs.

satisfies (TypeScript 4.9) checks whether a value matches a type without losing the more precise inferred type – ideal for configurations and lookup tables:

type Farbe = "rot" | "gruen" | "blau";
type RGB = [number, number, number];

const palette = {
  rot: [255, 0, 0],
  gruen: "#00ff00",
  blau: [0, 0, 255]
} satisfies Record<Farbe, string | RGB>;

console.log(palette.rot.at(0), palette.gruen.toUpperCase());
// With an annotation (: Record<...>) both values would only be "string | RGB".
// The compiler reports typos in keys or missing colors.

Branded types distinguish structurally identical types, such as amounts in euros and dollars or different kinds of IDs. The "brand" exists only in the type system:

type Euro = number & { readonly __marke: "Euro" };
type Dollar = number & { readonly __marke: "Dollar" };

const euro = (n: number) => n as Euro;
const dollar = (n: number) => n as Dollar;

function zahle(betrag: Euro): void {
  console.log("Paying " + betrag + " EUR");
}
zahle(euro(5));
// zahle(dollar(5));   // Error: Dollar is not Euro
// zahle(5);           // Error: number is not Euro

Overloads give a function several signatures but only one implementation. This way the return type depends on the argument type:

function parse(wert: string): number;
function parse(wert: string[]): number[];
function parse(wert: string | string[]): number | number[] {
  return Array.isArray(wert) ? wert.map(Number) : Number(wert);
}
const a = parse("42");            // number
const b = parse(["1", "2"]);      // number[]
console.log(a, b);

The result pattern makes errors part of the type instead of throwing exceptions. The compiler forces the caller to handle both cases:

type Ergebnis<T, E = string> =
  | { ok: true; wert: T }
  | { ok: false; fehler: E };

function teile(a: number, b: number): Ergebnis<number> {
  return b === 0
    ? { ok: false, fehler: "Division by zero" }
    : { ok: true, wert: a / b };
}
const e = teile(10, 0);
if (e.ok) console.log(e.wert);
else console.log("Error:", e.fehler);
TipThese patterns belong in your toolbox, not in every piece of code. Use them when a concrete problem (mix-ups, unchecked errors, imprecise types) justifies them.