Skip to content

Instantly share code, notes, and snippets.

@Harshkumar77
Last active August 8, 2023 15:07
Show Gist options
  • Save Harshkumar77/e296e5ad5566952a8edfba5536c36432 to your computer and use it in GitHub Desktop.
Save Harshkumar77/e296e5ad5566952a8edfba5536c36432 to your computer and use it in GitHub Desktop.
How to fetch in Typescript like pro ?
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);
}
})()
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment