Skip to content

Instantly share code, notes, and snippets.

@joshwashywash
Last active February 27, 2022 00:02
Show Gist options
  • Save joshwashywash/3abfbdffe6d1f5b8e844ffaedbe1a16a to your computer and use it in GitHub Desktop.
Save joshwashywash/3abfbdffe6d1f5b8e844ffaedbe1a16a to your computer and use it in GitHub Desktop.
create typesafe fetch in TypeScript

Just a higher-order function around fetch.

const createFetch = <T>(fn: (response: Response) => Promise<T>) => {
  return (...params: Parameters<typeof fetch>) => fetch(...params).then(fn);
};

You can use it like this:

const fetchJSON = createFetch(response => response.json());
fetchJSON('https://pokeapi.co/api/v2/pokemon/squirtle').then(console.log);

// logs whatever data came back from the pokeapi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment