Skip to content

CodeNot attempted

Typed fetch wrapper

Difficulty: easy

Write fetchJson<T>(url, init?), which returns Promise<T>, throws on a non-OK status (fetch only rejects on network errors) and passes init through. Then explain why the generic is a promise to the compiler, not a runtime check.

Show reference solution
// The <T> only says what we expect back. Nothing checks it at runtime.
export async function fetchJson<T>(url: string, init?: RequestInit): Promise<T> {
const response = await fetch(url, init);
if (!response.ok) {
throw new Error(`HTTP ${response.status} for ${url}`);
}
const data = await response.json();
return data as T;
}
Loading editor…