Async, APIs & Laufzeit-Validierung – TypeScript
Promise<T>, typisierte Fetch-Funktionen und warum Typen keine Daten prüfen.
Asynchrone Funktionen liefern ein Promise<T>. TypeScript prüft, dass du nach await mit dem entpackten Typ T arbeitest, und der Rückgabetyp einer async-Funktion ist immer ein Promise:
const warte = (ms: number): Promise<void> =>
new Promise((resolve) => setTimeout(resolve, ms));
async function ladeZahl(ms: number): Promise<number> {
await warte(ms);
return 42;
}
async function main(): Promise<void> {
const [a, b] = await Promise.all([ladeZahl(10), ladeZahl(20)]); // [number, number]
console.log(a + b);
}
main();Beim Laden von Daten aus dem Netz kennt TypeScript den Inhalt nicht: response.json() liefert any. Ein as Repo ist nur ein Versprechen an den Compiler – wenn die API etwas anderes schickt, merkt niemand etwas:
interface Repo {
full_name: string;
stargazers_count: number;
}
async function ladeRepo(name: string): Promise<Repo> {
const antwort = await fetch("https://api.github.com/repos/" + name);
if (!antwort.ok) throw new Error("HTTP " + antwort.status);
return (await antwort.json()) as Repo; // ungeprüft!
}Sicherer: Daten als unknown einlesen und mit einem Type Guard prüfen. Das ist der einzige Weg, wirklich zu wissen, was zur Laufzeit ankommt:
function istRepo(x: unknown): x is Repo {
if (typeof x !== "object" || x === null) return false;
const o = x as Record<string, unknown>;
return typeof o.full_name === "string" && typeof o.stargazers_count === "number";
}
async function ladeRepoSicher(name: string): Promise<Repo> {
const antwort = await fetch("https://api.github.com/repos/" + name);
const daten: unknown = await antwort.json();
if (!istRepo(daten)) throw new Error("Unerwartetes Antwortformat");
return daten;
}Für größere Datenmodelle schreibst du das Schema einmal mit einer Validierungsbibliothek (Zod, Valibot, ArkType) und leitest den Typ daraus ab – Laufzeitprüfung und Typ bleiben so automatisch gleich:
// npm install zod
import { z } from "zod";
const RepoSchema = z.object({
full_name: z.string(),
stargazers_count: z.number()
});
type Repo2 = z.infer<typeof RepoSchema>; // { full_name: string; stargazers_count: number }
const antwort = await fetch("https://api.github.com/repos/microsoft/TypeScript");
const repo = RepoSchema.parse(await antwort.json()); // wirft bei falschen Daten
console.log(repo.full_name);unknown – egal, was die Typannotation behauptet.Promise.all scheitert beim ersten Fehler komplett. Promise.allSettled liefert dagegen je Eintrag { status: "fulfilled", value } oder { status: "rejected", reason } – eine Discriminated Union, die du per status eingrenzt.