Using fetch with Typescript

Posted on 2/26/2024

async function fetchApi<T>(url: string): Promise<T> {
  const res = await fetch(url);
  if (res.ok) {
    return res.json() as Promise<T>;
  }
  throw new Error(res.statusText);
}
interface Product {
  id: number;
  title: string;
  description: string;
  price: number;
  discountPercentage: number;
  rating: number;
  stock: number;
  brand: string;
  category: string;
  thumbnail: string;
  images: string[];
}

async function consumeApi() {
  const result = await fetchApi<Product[]>("https://dummyjson.com/products");

  console.log(result);
}

consumeApi();

Sources:

Created with ❤️ using Next.js & Tailwind CSS