Create a generic fetchJson wrapper with typed response and error handling
marrying TypeScript generics to fetch for typed responses and runtime error handling.
generic T parameter, optional RequestInit, throw if !res.ok, return res.json() as Promise<T>.
using any or omitting the ok check.
What's really being asked
This question probes three distinct skills at the intersection of TypeScript and web APIs. First, it checks if you understand how to use generics to propagate type information from a caller down to an asynchronous return value. Second, it tests whether you know that fetch does not reject on HTTP error status codes like 404 or 500, so you must manually validate response.ok. Third, it reveals if you can write clean utility types that compose with standard DOM types like RequestInit.
The full answer
A strong implementation hits four things in order. First, the function signature should declare a generic T and accept a url string plus an optional init parameter typed as RequestInit. Second, inside the function, await the fetch call and check if the response.ok property is false. If it is, throw a new Error that includes the HTTP status or response.statusText so the caller knows the request failed. Third, only after the ok check should you call response.json and let TypeScript treat the result as T. Fourth, the return type should be explicitly Promise of T so the generic flows through to the caller.
The mistakes people make
The biggest red flag is forgetting that fetch resolves even on 500 status codes and skipping the response.ok guard entirely. Another frequent mistake is typing the return as Promise of any or leaving the generic unconstrained, which defeats the purpose of the exercise. Some candidates also try to cast the JSON result using as T after parsing instead of properly typing the promise chain, which is less idiomatic. Finally, avoid making init required; it should be optional with a default of an empty object or left as undefined.
What usually comes next
An interviewer might ask how you would extend this to support typed request bodies by making the init parameter conditional on the HTTP method. They could also ask you to add a timeout using AbortController, or to handle non-JSON responses gracefully by checking the Content-Type header before parsing. Another common follow-up is how to derive T automatically from an OpenAPI schema using conditional types and infer, which lets the path and method dictate the response type without manual generic arguments.
A concrete example
Here is a concise implementation in plain text. Declare an async function fetchJson with generic T, taking url as a string and init as an optional RequestInit, and returning Promise of T. Inside, await fetch with the url and init, then store the result as res. If res.ok is false, throw a new Error containing the status and statusText. Otherwise return res.json. A caller awaiting fetchJson with the explicit generic UserProfile on the endpoint slash api slash me receives a fully typed object with IntelliSense.
Interview question
In a generic fetchJson wrapper, why is it critical to check response.ok before returning res.json() as Promise<T>?
- a.Because fetch rejects its promise on HTTP error statuses, and the ok check is needed to intercept the rejection before parsing.
- b.Because TypeScript generics require runtime type guards; without checking ok, the compiler cannot verify that the JSON payload matches T.
- c.Because response.json() throws a SyntaxError when the server returns an error status, and ok prevents the exception.
- d.Because fetch resolves even on 4xx/5xx statuses, so skipping the check would return an error payload incorrectly typed as T.Correct
Why? this is the answer
fetch resolves successfully on HTTP error codes such as 404 or 500, so without the ok guard the caller would receive an error body wrongly typed as T. Option A is a tempting misconception because fetch only rejects on network failures, not on HTTP error statuses.
Just read this? Test yourself on what you have been reading.
Read the original → piccalil.li
You just looked this up. Could you explain it out loud?
That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on typescript — each one lists the topics its interview covers.
See open roles