DEV Community

Harshkumar77
Harshkumar77

Posted on

3

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
import { RandomUserAPIResponse, User } from "./types"
async function fetchRandomUser() {
try {
const response = await fetch('https://randomuser.me/api/')
const randomUser = await response.json() as RandomUserAPIResponse
return { user: randomUser.results[0] } as { success: true, user: User }
} catch (error) {
return { error } as { success: false, error: unknown }
}
}
(async () => {
const userResponse = await fetchRandomUser()
if (userResponse.success) {
console.log(userResponse.user);
} else {
console.error(userResponse.error);
}
})()
view raw index.ts hosted with ❤ by GitHub
export interface RandomUserAPIResponse {
results: User[];
info: Info;
}
export interface Info {
seed: string;
results: number;
page: number;
version: string;
}
export interface User {
gender: string;
name: Name;
location: Location;
email: string;
login: Login;
dob: Dob;
registered: Dob;
phone: string;
cell: string;
id: ID;
picture: Picture;
nat: string;
}
export interface Dob {
date: Date;
age: number;
}
export interface ID {
name: string;
value: string;
}
export interface Location {
street: Street;
city: string;
state: string;
country: string;
postcode: string;
coordinates: Coordinates;
timezone: Timezone;
}
export interface Coordinates {
latitude: string;
longitude: string;
}
export interface Street {
number: number;
name: string;
}
export interface Timezone {
offset: string;
description: string;
}
export interface Login {
uuid: string;
username: string;
password: string;
salt: string;
md5: string;
sha1: string;
sha256: string;
}
export interface Name {
title: string;
first: string;
last: string;
}
export interface Picture {
large: string;
medium: string;
thumbnail: string;
}
view raw types.ts hosted with ❤ by GitHub

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay