TypeScript: Generics – code examples
Contents
Generic function
Generics#generics#type parameter#inference
Use case: Helper functions that work safely with arbitrary types (first, groupBy, wrap).
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]));T is inferred from the argument; the return type adapts. The tuple [A, B] preserves the order of the types.
Generics with constraints (extends, keyof)
Generics#generics#extends#keyof
Use case: Functions that only work with certain shapes, or type-safe property access.
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]));
function eigenschaft<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
console.log(eigenschaft({ name: "Ada", alter: 36 }, "alter"));extends { length: number } allows strings and arrays, but not numbers. K extends keyof T allows only existing keys and returns the matching value type.
Utility types in practice
Generics#partial#pick#omit#returntype
Use case: Derive update and preview types from a data model instead of maintaining them twice.
interface Produkt {
id: number;
name: string;
preis: number;
lager: number;
}
type ProduktUpdate = Partial<Omit<Produkt, "id">>;
type Vorschau = Pick<Produkt, "name" | "preis">;
function aktualisiere(p: Produkt, u: ProduktUpdate): Produkt {
return { ...p, ...u };
}
const kaffee: Produkt = { id: 1, name: "Coffee", preis: 4.5, lager: 20 };
console.log(aktualisiere(kaffee, { preis: 4.99 }));
const vorschau: Vorschau = { name: "Coffee", preis: 4.5 };
type Rueckgabe = ReturnType<typeof aktualisiere>; // ProduktOmit removes id, Partial makes the rest optional. If Produkt changes, the derived types change automatically with it.
Generic class (stack)
Generics#generics#class#stack
Use case: Build reusable data structures: stack, queue, cache, repository.
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 s = new Stapel<number>();
s.push(1);
s.push(2);
// s.push("x"); // compiler error
console.log(s.pop(), s.groesse);The type parameter T determines what is in the stack. pop returns T | undefined because the stack can be empty – the compiler reminds you to check for that.