TypeScript
Public
Typed JSON Fetch Helper
Wrap fetch with JSON parsing, typed responses, and useful HTTP error messages.
#typescript
#fetch
#api
#json
TypeScript
type ApiErrorBody = {
message?: string;
};
export async function fetchJson<T>(
input: RequestInfo | URL,
init?: RequestInit,
): Promise<T> {
const response = await fetch(input, {
...init,
headers: {
Accept: 'application/json',
...init?.headers,
},
});
const contentType = response.headers.get('content-type') ?? '';
const isJson = contentType.includes('application/json');
const body = isJson
? await response.json()
: null;
if (!response.ok) {
const errorBody = body as ApiErrorBody | null;
throw new Error(
errorBody?.message
?? `Request failed with status ${response.status}.`,
);
}
return body as T;
}