Sequence NODE_179
Medium

Add Types to a Fetch Wrapper Function

TypeScript
Technical Specification

Write a generic fetchJson<T> function that fetches a URL and returns Promise<T>.

Input/Output Samples
Input:fetchJson<User[]>('/api/users')
Output:Promise<User[]>
Optimal Logic Path
async function fetchJson<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (!res.ok) {
    throw new Error("Request failed");
  }
  return res.json() as Promise<T>;
}
Architectural Deep-Dive
Generics let us specify the expected response type at call site, giving full IntelliSense and type safety.