TSTypeScript
IntermediateLesson 7 of 15

Generics – TypeScript

Reusable functions and classes that work with many types.

Generics are type placeholders. A function like erstes should work for any array – and still return the correct element type. T is inferred at the call:

function erstes<T>(liste: T[]): T | undefined {
  return liste[0];
}
const n = erstes([1, 2, 3]);        // number | undefined
const s = erstes(["a", "b"]);       // string | undefined
console.log(n, s, erstes([]));

function tausche<A, B>(paar: [A, B]): [B, A] {
  return [paar[1], paar[0]];
}
console.log(tausche(["x", 1]));     // [1, "x"]

With extends you restrict what is allowed for T. keyof and indexed access make type-safe property access possible:

function laengster<T extends { length: number }>(a: T, b: T): T {
  return a.length >= b.length ? a : b;
}
console.log(laengster("short", "longer"), laengster([1, 2, 3], [1]));
// laengster(5, 6);   // Error: number has no 'length'

function eigenschaft<T, K extends keyof T>(objekt: T, schluessel: K): T[K] {
  return objekt[schluessel];
}
const alter = eigenschaft({ name: "Ada", alter: 36 }, "alter");   // number
// eigenschaft({ name: "Ada" }, "farbe");   // Error: "farbe" is not a key

Interfaces, type aliases and classes can also be generic – and type parameters may have default values:

interface Antwort<T = unknown> {
  daten: T;
  status: number;
}
const a: Antwort<string[]> = { daten: ["x"], status: 200 };

class Stapel<T> {
  private items: T[] = [];
  push(item: T): void { this.items.push(item); }
  pop(): T | undefined { return this.items.pop(); }
  get groesse(): number { return this.items.length; }
}
const s2 = new Stapel<number>();
s2.push(1);
s2.push(2);
// s2.push("x");    // Error
console.log(s2.pop(), s2.groesse);
TipKeep generics simple: a type parameter that appears only once is superfluous. Use meaningful names (TItem, TKey) as soon as there are more than two.