AdvancedLesson 15 of 15
Async, APIs & Runtime Validation – TypeScript
Promise<T>, typed fetch functions and why types do not check data.
Asynchronous functions return a Promise<T>. TypeScript checks that after await you work with the unwrapped type T, and the return type of an async function is always a 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();When loading data from the network, TypeScript does not know the content: response.json() returns any. An as Repo is only a promise to the compiler – if the API sends something else, nobody notices:
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; // unchecked!
}Safer: read data as unknown and check it with a type guard. This is the only way to really know what arrives at runtime:
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;
}For larger data models you write the schema once with a validation library (Zod, Valibot, ArkType) and derive the type from it – runtime check and type then automatically stay the same:
// 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()); // throws on wrong data
console.log(repo.full_name);WarningTypes are gone after compilation. Everything that comes from outside (JSON, forms, URL parameters, environment variables) is only
unknown until it has been checked – no matter what the type annotation claims.Tip
Promise.all fails completely at the first error. Promise.allSettled, on the other hand, returns { status: "fulfilled", value } or { status: "rejected", reason } per entry – a discriminated union that you narrow by status.