There is generic get method defined in axios/index.d.ts

get<T = never, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): Promise<R>;

Example

interface User {
    id: number;
    firstName: string;
}


axios.get<User[]>('http://localhost:8080/admin/users')
        .then(response => {
            console.log(response.data);
            setUserList( response.data );
        });

I think you are passing list the wrong way to child component.

const [users, setUserList] = useState<User[]>([]);
<UserList items={users} />
interface UserListProps {
    items: User[];
};
const UserList: React.FC<UserListProps> = ({items}) => {
    return (
        <Fragment>
            <ul>
            {items.map(user => (
                <li key={user.id}>
                    <span>{user.firstName}</span>
                </li>
            ))}
            </ul>
        </Fragment>
    );
};
Answer from Józef Podlecki on Stack Overflow
🌐
BezKoder
bezkoder.com › home › react typescript example project with axios and web api
React Typescript example Project with Axios and Web API - BezKoder
December 12, 2022 - In this tutorial, I will show you how to build a React Typescript example Project with Axios consume Web API, display and modify data with Router & Bootstrap.
🌐
GitHub
github.com › bezkoder › react-axios-typescript-example
GitHub - bezkoder/react-axios-typescript-example: Build React Typescript example Project - CRUD with Axios and make Web API call · GitHub
Build a React Typescript and Axios CRUD example to consume Web API with Router & Bootstrap 4.
Starred by 42 users
Forked by 39 users
Languages   TypeScript 88.3% | HTML 8.9% | CSS 2.8%
🌐
npm
npmjs.com › package › axios
axios - npm
4 days ago - If you use TypeScript to type check CJS JavaScript code, your only option is to use "moduleResolution": "node16". You can also create a custom instance with typed interceptors: import axios, { AxiosInstance, InternalAxiosRequestConfig } from "axios"; const apiClient: AxiosInstance = axios.create({ baseURL: "https://api.example.com", timeout: 10000, }); apiClient.interceptors.request.use((config: InternalAxiosRequestConfig) => { // Add auth token return config; });
      » npm install axios
    
Published   Apr 08, 2026
Version   1.15.0
🌐
Medium
medium.com › @ignatovich.dm › creating-a-type-safe-api-client-with-typescript-and-react-ce1b82bf8b9b
Creating a Type-Safe API Client with TypeScript and React | by Frontend Highlights | Medium
October 11, 2024 - With axios or fetch, TypeScript allows us to define strict types for both request and response structures, reducing bugs and providing better development tools (like autocompletion and type-checking).
🌐
Educative
educative.io › answers › typescript-react---fetch-array-data-using-axios
Typescript React - Fetch array data using Axios
This is a quick post to help detail how you can fetch data from an API without Typescript shouting at you! It explains how to fetch data using Axios and how to set it to variables with defined Types as required by Typescript. For this example, our app will be made with Typescript and React.
Top answer
1 of 2
136

There is generic get method defined in axios/index.d.ts

get<T = never, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig<T>): Promise<R>;

Example

interface User {
    id: number;
    firstName: string;
}


axios.get<User[]>('http://localhost:8080/admin/users')
        .then(response => {
            console.log(response.data);
            setUserList( response.data );
        });

I think you are passing list the wrong way to child component.

const [users, setUserList] = useState<User[]>([]);
<UserList items={users} />
interface UserListProps {
    items: User[];
};
const UserList: React.FC<UserListProps> = ({items}) => {
    return (
        <Fragment>
            <ul>
            {items.map(user => (
                <li key={user.id}>
                    <span>{user.firstName}</span>
                </li>
            ))}
            </ul>
        </Fragment>
    );
};
2 of 2
16

You need to provide a type argument when calling axios.get if you do not want Axios to infer the type for the value response as any.

And you are passing an incorrect type argument when you useState to create the array of users.

The correct way

interface User {
  id: number;
  firstName: string;
}

// Initialized as an empty array
const [users, setUserList] = useState<User[]>([]); // 'users' will be an array of users

For example,

import React, {useEffect, useState, Fragment } from 'react';
import UserList from './UserList';
import axios from 'axios';

interface User {
  id: number;
  firstName: string;
}

// You can export the type TUserList to use as -
// props type in your `UserList` component
export type TUserList = User[]

const Users: React.FC = (props) => {
   // You can also use User[] as a type argument
    const [users, setUserList] = useState<TUserList>();

    useEffect(() => {
        // Use [] as a second argument in useEffect for not rendering each time
        axios.get<TUserList>('http://localhost:8080/admin/users')
        .then((response) => {
            console.log(response.data);
            setUserList(response.data);
        });
    }, []);

    return (
        <Fragment>
            <UserList {...users} />
        </Fragment>

    );
};
export default Users;

If you choose to export the type type TUserList = User[], you can use it in your UserList component as the type for props. For example,

import React, {Fragment } from 'react';
import { TUserList } from './Users';

interface UserListProps {
    items: TUserList // Don't have to redeclare the object again
};

const UserList: React.FC<UserListProps> = (props) => {
    return (
        <Fragment>
            <ul>
            {props.items.map(user => (
                <li key={user.id}>
                    <span>{user.firstName}</span>
                    { /* Do not call the delete function. Just point
                         to it. Set this to null in bind(). */}
                </li>
            ))}
            </ul>
        </Fragment>
    );
};

export default UserList;
🌐
Bionicjulia
bionicjulia.com › blog › axios-wrappers-react-typescript
Axios Wrappers in React Typescript - Bionic Julia
February 20, 2021 - To start, we create an ApiClient class. This class contains a private property client which is of type AxiosInstance. It also has a protected method createAxiosClient that takes in apiConfiguration parameters to create an axios client (e.g. ...
🌐
DhiWise
dhiwise.com › post › exploring-the-possibilities-of-axios-with-typescript
Use of Axios with Typescript in React Apps
November 2, 2023 - Axios with TypeScript is a winning combination for React professionals for managing HTTP requests. Learn about Axios TypeScript in React applications.
Find elsewhere
🌐
CodeSandbox
codesandbox.io › s › react-typescript-axios-phc0l
React Typescript Axios - CodeSandbox
May 12, 2021 - React Typescript Axios by purvasheth using axios, react, react-dom, react-scripts
Published   May 12, 2021
Author   purvasheth
🌐
Upmostly
upmostly.com › home › typescript › how to use axios
How to Use Axios in Your TypeScript Apps - Upmostly
December 8, 2022 - Today I’ll talk you through using TypeScript with Axios, by providing a type to their generic functions, and how they work together.
🌐
GitHub
github.com › bezkoder › react-query-axios-typescript
GitHub - bezkoder/react-query-axios-typescript: React Query, Axios, Typescript example: get, post, put, delete - useQuery, useMutation, error handling
React Client with React Query and Axios (Typescript) to make CRUD requests to Rest API in that:
Starred by 50 users
Forked by 20 users
Languages   TypeScript 86.9% | HTML 10.8% | CSS 2.3% | TypeScript 86.9% | HTML 10.8% | CSS 2.3%
🌐
DEV Community
dev.to › tuasegun › cleaner-and-better-way-for-calling-apis-with-axios-in-your-react-typescript-applications-3d3k
Cleaner and Better way for calling APIs with Axios in your React-typescript applications - DEV Community
November 2, 2022 - How to create react app ... The package we will be using is Axios - Axios is a Javascript library used to make Http requests in nodeJS or XMLHttpRequests from the browser that also supports the ES6 Promise API.
🌐
LinkedIn
linkedin.com › pulse › mastering-http-requests-javascript-axios-typescript-novin-noori
Mastering HTTP Requests in JavaScript with Axios and TypeScript
March 15, 2023 - To start using Axios in your React TypeScript project, you must install it using a package manager such as npm, yarn or pnpm.
🌐
DEV Community
dev.to › charlintosh › setting-up-axios-interceptors-react-js-typescript-12k5
Setting up Axios Interceptors (React.js + TypeScript) - DEV Community
September 29, 2020 - Axios have a way to add interceptors to an Axios Instance, which basically are a callback functions that will be executed before a request or after response occurs. A basic interceptor example [1] is: The idea is add the log() (or the you want as debug(), info(), warn()) right here. This will be helpful to avoid putting these lines on every particular request or response we do. In this example, I’m using React + TypeScript (and obviously, ES6), but It must be similar doing without this configuration and simple JavaScript.
🌐
JavaScript in Plain English
javascript.plainenglish.io › axios-a-simple-and-effective-way-to-make-api-calls-in-react-with-typescript-f0b1e7eebdc5
Axios: A Simple and Effective Way to Make API Calls in React with TypeScript | by Damilola Esan | JavaScript in Plain English
November 9, 2023 - In fact, Axios is one of the most popular libraries for making API calls in React with TypeScript, according to a survey by Stack Overflow. In this guide, I will show you how to set up Axios in your React app with TypeScript and use it to make API calls with ease.
🌐
GitHub
github.com › bezkoder › react-typescript-api-call
GitHub - bezkoder/react-typescript-api-call: React Typescript with API call example using Hooks and Axios, Router & Bootstrap · GitHub
Build a React Typescript CRUD Application to consume Web API with Hooks and Axios, display and modify data with Router & Bootstrap.
Starred by 45 users
Forked by 26 users
Languages   TypeScript 86.4% | HTML 10.3% | CSS 3.2% | Shell 0.1%
🌐
BezKoder
bezkoder.com › home › react query and axios (typescript) example with rest api
React Query and Axios (Typescript) example with Rest API - BezKoder
December 12, 2022 - React Query, Axios, Typescript example: get, post, put, delete - React Query Typescript examples: useQuery, useMutation, error handling
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-http-request-axios
Making HTTP requests with Axios in TypeScript | bobbyhadz
February 27, 2024 - If you'd rather use the built-in fetch module to make HTTP requests in TypeScript, check out the following article. You can learn more about the related topics by checking out the following tutorials: How to change the Base URL in Axios [4 ways] How to fetch Data on Button click in React ·
Top answer
1 of 1
16

The reason is in this line:

const [data, setData] = useState(null)

Because there is no type parameter provided explicitly for useState, TypeScript infers the type of data based on the type of initial state. In this case, the initial state is null and TypeScript treats this type as the only possible state.

You know that the state will either be null or something else — but TypeScript doesn't. Let's use type parameters to tell it what's really going on.

const [data, setData] = useState<AxiosResponse | null | void>(null);

This gets rid of the error, but looks strange — why is void there? The reason for that is that you catch before you then — and since catch emits a side effect (returns void, in other words), the type propagated to catch is either void or AxiosResponse. Let's fix that by replacing then and catch.

The final solution:

import axios, { AxiosResponse } from "axios";
import { useEffect, useState } from "react";

const useAxiosFetch = (url: string, timeout: number) => {
  const [data, setData] = useState<AxiosResponse | null>(null);
  const [error, setError] = useState(false);
  const [errorMessage, setErrorMessage] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let unmounted = false;
    const source = axios.CancelToken.source();
    axios
      .get(url, {
        cancelToken: source.token,
        timeout,
      })
      .then(a => {
        if (!unmounted) {
          setData(a);
          setLoading(false);
        }
      })
      .catch(function(e) {
        if (!unmounted) {
          setError(true);
          setErrorMessage(e.message);
          setLoading(false);
          if (axios.isCancel(e)) {
            console.log(`request cancelled:${e.message}`);
          } else {
            console.log("another error happened:" + e.message);
          }
        }
      });

    return function() {
      unmounted = true;
      source.cancel("Cancelling in cleanup");
    };
  }, []);

  return { data, loading, error, errorMessage };
};

export default useAxiosFetch;

🌐
Geshan
geshan.com.np › blog › 2023 › 11 › axios-typescript
How to use Axios with Typescript a beginner’s guide
November 7, 2023 - That covers the basics of using Axios with TypeScript to make API calls and handle the response data. You have learned the basics of Axios and its types for making a GET and a POST call in a TypeScript environment. The example is executed on a Node.js environment but it should work the same on a browser too as Axios runs on both the server and the client.