How to Use fetch with TypeScript

The main problem with fetch function is that it isn't a generic function. This makes it harder to type response data without writing additional wrappers.

We can create a wrapper-module to avoid this problem.

Wrapper Module#

Let's create a function request that will handle network requests:

Now we can call this function as we would call fetch:

Or, since it is an async function we can use await:

Error Handling#

Right now the request function doesn't handle errors. To solve that we have 2 options:

  • Handle errors inside of the request function;

  • Let another module handle errors.

There are no obligatory rules for this but Single Responsibility Principle tells us not to mix those concerns in a single function.

However, we will take a look at both ways. The first one is to handle errors inside of the request function:

We can use catch to handle unresolved promises. There is a catch though (no pun intended).

  • We can pass incorrect arguments to fetch and error will arise before the very first then;

  • We may even not know how to handle an error in catch yet ¯\_(ツ)_/¯

The first issue we can solve making the function async and using try-catch:

However, this doesn't solve the second issue with not knowing how to handle the error. We can handle some basic network errors (Page Not Found, Bad Request) but we cannot handle any business-logic errors.

With async/await approach, we can handle errors outside of the request function:

API Module#

We can also pre-define some basic request-methods, like get and post:

We will use them like this:

Key Takeaways#

  • The fetch function is not generic.

  • To type the response result we need to create a wrapper generic-function ourselves.

  • We can handle errors in that same wrapper or outside. Either approach has pros and cons.

  • We can use then as well as await with Promise-based functions but await is a bit more convenient when it comes to error handling.