TypeScript: Types – code examples
Interface, Type Alias & Intersection
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
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
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
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
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
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.