1 ) Using Axios with TypeScript

Why Axios?

Axios is a popular HTTP client that works in both Node.js and the browser. The good news is Axios already ships with built-in TypeScript type definitions, so you don’t need to install them separately.

Just install it with:


npm install axios

You can explore this repo (look for .d.ts files (these are declaration files that describe the shapes of objects/functions for TypeScript).)

https://github.com/DefinitelyTyped/DefinitelyTyped

First, you have to install axios library npm i axios

now , Let’s use this free placeholder API to simulate fetching a TODO item: https://jsonplaceholder.typicode.com/todos/1

Try opening this in your browser you'll see the following JSON response:

image.png

Step 1: Create an Interface

Based on the API response, define a TypeScript interface to describe the structure of a TODO item:

interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

Step 2: Write the Axios Function with Proper Typing

import axios, { AxiosResponse } from "axios";

interface Todo {
  userId: number;
  id: number;
  title: string;
  completed: boolean;
}

const fetchData = async () => {
  try {
    const response: AxiosResponse<Todo> = await axios.get(
      "https://jsonplaceholder.typicode.com/todos/1"
    );
    console.log("Todo", response.data);
  } catch (error: any) {
    if (axios.isAxiosError(error)) {
      console.log("Axios Error", error.message);

      if (error.response) {
        console.log("Status", error.response.status);
        console.log("Data", error.response.data);
      }
    } else {
      console.log("Error", error.message);
    }
  }
};

fetchData();