tezvyn:

Create a generic fetchJson wrapper with typed response and error handling

Source: piccalil.liintermediate

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 IT TESTS: bridging TypeScript generics with the Fetch API to enforce compile-time JSON types alongside runtime error handling for non-ok responses. ANSWER OUTLINE: first, declare a generic T and an optional RequestInit parameter; second, await fetch then throw a descriptive error if response.ok is false; third, return response.json() as Promise<T> so consumers receive a strongly typed result. RED FLAG: typing the return as Promise<any>, omitting the response.ok guard, or casting the parsed body instead of leveraging the generic.

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.

Create a generic fetchJson wrapper with typed response and error handling · Tezvyn