Created
January 13, 2025 18:31
-
-
Save joemaffei/bf23b31cf2a5c00b71d30b882c8f4d23 to your computer and use it in GitHub Desktop.
Fetch with typed response, throws on errors
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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