DEV Community

Harshkumar77
Harshkumar77

Posted on

How to fetch in Typescript like pro ?

No BS guide to use fetch API typescript way.
This article is for you if :

  • You know how to use fetch API
  • Don't want a try and catch hell // Excellent error handling
  • Don't want to write types
  • Move fast
  • Easy understandable code

How ?

  1. Understand what you want to extract from API.
  2. Generate types from https://jsonformatter.org/json-to-typescript
  3. Just paste it there and it will generate all the types for you.
  4. Rename the types and rename if required
  5. we are using https://randomuser.me/api/ so go ahead and paste it
  6. Fetch the data in following way

The article is done here its a simple type inferring pattern but if you want to understand why read down.

Why ?

1. Encapsulating functions

  • It makes code easy to read
  • Can be reused

2. What's that typescript wizardry 🧙‍♂️ you are doing ?

You will understand it by watching these screenshots

Image description

The inferred type here is a union which provide this awesome typescript code flow


User field is only available when success is true

Image description
Error field is only available when success is true

Top comments (2)

Collapse
 
harshkumar77 profile image
Harshkumar77

The title is definitely clickbait-ey. I just wanted to present this pattern which uses typescript flow for autocompletion. My code might be little bit more verbose but its well readable. Also I think promise chaining is an hell of itself.

Collapse
 
alakkadshaw profile image
alakkadshaw

Hi Welcome to the community