How to Use fetch with TypeScript

Responses (6)

p

Shouldn't the response error (response.ok) still be handled inside the request function?

However, we will take a look at both ways.
Kostas Minaidis3 months ago

There's a typo in the code below: Promise<TReponse> should be Promise<TResponse>

Clap
4|6|

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: