tezvyn:

Create a generic fetchJson wrapper with typed response and error handling

AI-drafted, machine-checkedSource: piccalil.liintermediate
Create a generic fetchJson wrapper with typed response and error handling
WHAT IT TESTS

marrying TypeScript generics to fetch for typed responses and runtime error handling.

ANSWER OUTLINE

generic T parameter, optional RequestInit, throw if !res.ok, return res.json() as Promise<T>.

RED FLAG

using any or omitting the ok check.

WHAT THIS TESTS: 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.

A GOOD ANSWER COVERS: 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.

COMMON WRONG ANSWERS: 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.

LIKELY FOLLOW-UPS: 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.

ONE 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.

Source: piccalil.li

Read the original → piccalil.li

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.