Skip to content

Instantly share code, notes, and snippets.

@joemaffei
Created January 13, 2025 18:31
Show Gist options
  • Save joemaffei/bf23b31cf2a5c00b71d30b882c8f4d23 to your computer and use it in GitHub Desktop.
Save joemaffei/bf23b31cf2a5c00b71d30b882c8f4d23 to your computer and use it in GitHub Desktop.
Fetch with typed response, throws on errors
interface TypedResponse<TJson> extends globalThis.Response {
json: () => Promise<TJson>;
}
async function typedFetch<T>(...args: Parameters<typeof fetch>) {
const response = await fetch(...args);
if (!response.ok) throw response;
return response as TypedResponse<T>;
}
// EXAMPLE
class PersonNotFoundError extends Error {}
type Person = {
result: {
properties: {
name: string;
url: string;
}
}
}
(async function test() {
try {
// SUCCESS
const test = await typedFetch<Person>("https://www.swapi.tech/api/people/1");
// NOT FOUND
// const test = await typedFetch<Person>("https://www.swapi.tech/api/people/1000");
const json = await test.json();
console.log(json.result);
} catch (error) {
if (error instanceof Response) {
if (error.status === 404) {
throw new PersonNotFoundError();
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment