CódigoSin intentar
Envoltorio tipado de fetch
Dificultad: fácil
Escribe fetchJson<T>(url, init?), que devuelve Promise<T>, lanza un error si el estado no es OK (fetch solo se rechaza con errores de red) y pasa init tal cual. Luego explica por qué el genérico es una promesa al compilador y no una comprobación en ejecución.
Ver solución de referencia
// 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;}
Ctrl Enter