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 ?
- Understand what you want to extract from API.
- Generate types from https://jsonformatter.org/json-to-typescript
- Just paste it there and it will generate all the types for you.
- Rename the types and rename if required
- we are using https://randomuser.me/api/ so go ahead and paste it
- 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
The inferred type here is a union which provide this awesome typescript code flow
Top comments (2)
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.
Hi Welcome to the community