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
🌐
npm
npmjs.com › package › @types › axios
types/axios
October 23, 2024 - Author message:This is a stub types definition. axios provides its own type definitions, so you do not need this installed.
      » npm install @types/axios
    
Published   Oct 23, 2024
Version   0.14.4
🌐
Stack Overflow
stackoverflow.com › questions › 76941578 › typescript-axios-types
Typescript: Axios types - javascript
import { AxiosInstance, AxiosResponseHeaders, AxiosRequestConfig, AxiosResponse, AxiosError, } from 'axios' interface ErrorResponse { data: null status: number statusText: string headers: AxiosResponseHeaders config: AxiosRequestConfig } interface PayloadType<T> { [key: string]: T } export default class Axios { axios: AxiosInstance = window.axios async get<T>(route: string): Promise<T | ErrorResponse> { try { const { data } = await this.axios.get<T>(route) return data } catch (error) { return this.handleErrorResponse<T>(error) } } async post<T>( route: string, payload: PayloadType<T> ): Promis
Discussions

How to Type Axios.js 'AxiosResponse' data generic
axios.get()? More on reddit.com
🌐 r/typescript
6
6
August 4, 2021
How to use Axios with TypeScript when using response interceptors (AxiosResponse issue)
In a project I am migrating to TypeScript (TS), I have a response interceptor r => r.data. How do I inform TS that I am not expecting a type of AxiosResponse? I've tried overriding using as Array<... but that doesn't work as AxiosResponse can't be cast as an Array (e.g. More on github.com
🌐 github.com
50
April 30, 2018
typescript - How to correctly use and install Axios - Stack Overflow
Hi, if I import by some reason ... "axios". Relative references must start with either "/", "./", or "../". And that's because the client can't find the library. That happened to me also for bootstrap and jquery in TS, that's why I added those in the type array in tsconfig 2022-12-31T16:17:57.557Z+00:00 ... If you're loading it in the browser, you probably need to use a bundler like webpack to create a JS file containing your typescript code and these ... More on stackoverflow.com
🌐 stackoverflow.com
Typescript types do not make sense
Describe the bug I updated from axios 0.21.1 to 0.22.0 but typescript started giving me strange errors I then noticed that the types declarations changed and they do not make much sense. I can see ... More on github.com
🌐 github.com
18
October 11, 2021
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;
🌐
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 TypeScript, we can define types that match the API’s expected request and response structures. This helps to: Catch errors early in development. Provide better autocompletion and hints in IDEs. Ensure data consistency across components. ... Then, create an apiClient.ts file for your reusable API client logic. We’ll start by creating a simple API client using Axios.
🌐
DEV Community
dev.to › shiftyp › my-type-of-library-axios-typescript-conversion-3m6j
My Type of Library: Axios TypeScript Conversion - DEV Community
April 1, 2025 - We know this because it's in the type definitions that exist already in Axios. I also know this because a search of the codebase reveals that the string doesn't appear in any other context in relation to a ResponseType. This line existed in the original PR, and was actually modified in a second pr to fix a bug, but in both cases this comparison appears. Maybe it was an addition for an idea that was never completed or wasn't needed by the end of the PR, but either way TypeScript tells us its probably a mistake.
🌐
Reddit
reddit.com › r/typescript › how to type axios.js 'axiosresponse' data generic
r/typescript on Reddit: How to Type Axios.js 'AxiosResponse' data generic
August 4, 2021 -

Hi all!

I'm using the axios http library for Node to make requests to a public API as follows:

const response = await axios.get(url)

logPaginatedResponse(response)

After receiving a response and storing it in the response variable above, I am passing the variable to the logPaginatedResponse function to log the response to the console.

My logPaginatedResponse function looks like this:

import { AxiosResponse } from "axios"

export const logPaginatedResponse = async (response: AxiosResponse) => {
  console.dir({
    total_records: response.data.meta.pagination.total,
    records_per_page: response.data.meta.pagination.per_page,
    current_page: response.data.meta.pagination.current_page,
    total_pages: response.data.meta.pagination.total_pages,
  })
}

The AxiosResponse interface looks like this:

export interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

In the logPaginatedResponse, I am trying to get autocompletion for response.data.meta.pagination.total, response.data.meta.pagination.per_page, etc.

The AxiosResponse interface gives me autocompletion for response, but no autocompletion for anything in the data object.

The problem is, the data object on the response could be one of many interfaces. See below:

interface CustomerResponse {
  data: {
    customer_id: number
  },
  meta: {
    pagination: {
      total: number,
      count: number,
      per_page: number,
      current_page: number,
      total_pages: number,
      links: {
        previous: string,
        current: string,
        next: string
      }
    }
  },
}

interface ProductResponse {
  data: {
    product_id: number
  },
  meta: {
    pagination: {
      total: number,
      count: number,
      per_page: number,
      current_page: number,
      total_pages: number,
      links: {
        previous: string,
        current: string,
        next: string
      }
    }
  },
}

export const logPaginatedResponse = async (response: AxiosResponse<CustomerResponse | ProductResponse>) => { // console.dir here }

Is there any way to give logPaginatedResponse either the CustomerResponse or ProductResponse interface dynamically?

I tried passing CustomerResponse or ProductResponse to the logPaginatedResponse function at the time of function invocation as follows:

const response = await axios.get(url)

logPaginatedResponse<CustomerResponse>(response)

But that isn't doing the trick. Is this not possible? It almost sounds like I'm looking for what this SO post describes: https://stackoverflow.com/a/50512697 but I'm not entirely sure.

Any suggestions would be super appreciated!! Thank you so much.

EDIT:

I ended up refactoring per u/__gc's suggestion in the comments

🌐
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.
Find elsewhere
🌐
Axios
axios.rest › pages › getting-started › examples › typescript
TypeScript example | axios | promise based HTTP client
For example, you can type a request like so: ... import axios, { AxiosRequestConfig, AxiosResponse } from "axios"; type Post = { userId: number; id: number; title: string; body: string; }; const getPosts = async (postId: number): Promise<AxiosResponse<Post>> => { return axios().get("https://jsonplaceholder.typicode.com/posts", { params: { postId, }, }); };
🌐
Delft Stack
delftstack.com › home › howto › typescript › axios typescript
How to Use Axios in TypeScript | Delft Stack
February 2, 2024 - Thus, one can either put the baseURL or the full URL as part of the request. One of the critical things to notice here is the data field in AxiosRequestConfig and AxiosResponse, which are generic types T and can accept any type. The above types can make typed REST API calls in TypeScript.
🌐
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.
🌐
Revathskumar
blog.revathskumar.com › 2023 › 04 › typescript-add-types-for-axios-response-data-and-error-data.html
TypeScript: add types for axios response data and error data
April 17, 2023 - When using axios with TypeScript, one major problem we face is the types for the response data and error data. Consider the below function, which uses axios.post · async function postHello() { try { const response = await axios.post('/hello', {}); console.log(response.data); } catch (error) { console.log(error.response.data.status); } } In the above function, the type of data will be any which can’t ensure the type safety.
🌐
GitHub
github.com › axios › axios › issues › 1510
How to use Axios with TypeScript when using response interceptors (AxiosResponse issue) · Issue #1510 · axios/axios
April 30, 2018 - In a project I am migrating to TypeScript (TS), I have a response interceptor r => r.data. How do I inform TS that I am not expecting a type of AxiosResponse? I've tried overriding using as Array<... but that doesn't work as AxiosResponse can't be cast as an Array (e.g.
Author   rssfrncs
🌐
DEV Community
dev.to › limacodes › why-using-axios-with-typescript-1fnj
Why using AXIOS with Typescript? - DEV Community
February 10, 2023 - Always define interfaces for the data types that your API is expected to return, and use them to type-check the response data. This will help you catch any errors early on and make your code more maintainable. interface User { id: number name: string } interface ApiResponse { data: User[] status: number } const getUsers = async (): Promise<ApiResponse> => { const { data } = await axios.get<ApiResponse>('https://my-api.com/users') return data } Follow best practices for error handling when working with APIs in TypeScript.
🌐
Apidog
apidog.com › blog › axios-typescript
How to Use Axios and Typescript to Build APIs
February 5, 2026 - Fortunately, there is a solution to this problem, and that is to use a library called axios-typescript. Axios-typescript is a wrapper around axios that adds type definitions and generics to the axios methods, making them type-safe and easy to use with typescript.
🌐
Bobby Hadz
bobbyhadz.com › blog › typescript-http-request-axios
Making HTTP requests with Axios in TypeScript | bobbyhadz
February 27, 2024 - Examples of how to make HTTP requests with Axios in TypeScript, including GET, POST, PATCH, PUT and DELETE requests.
🌐
OpenAPI Generator
openapi-generator.tech › docs › generators › typescript-axios
Documentation for the typescript-axios Generator | OpenAPI Generator
February 10, 2026 - These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to configuration docs for more details
🌐
GitHub
github.com › axios › axios › issues › 4176
Typescript types do not make sense · Issue #4176 · axios/axios
October 11, 2021 - post<T = never, R = AxiosResponse<T>>(url: string, data?: T | undefined, config?: AxiosRequestConfig<T> | undefined): Promise<R>
Author   euberdeveloper
🌐
GitHub
github.com › axios › axios › issues › 3612
How to type axios error in Typescript? · Issue #3612 · axios/axios
January 30, 2021 - Describe the issue I have question how type axios error in Typescript. I know AxiosError type is exposed, but I don't think it should be used because it's unclear if it's an Axios Error when caught. Example Code import axios, {AxiosError...
Author   EkeMinusYou
🌐
Medium
enetoolveda.medium.com › how-to-use-axios-typescript-like-a-pro-7c882f71e34a
How to Use Axios/Typescript like a pro! (axios-es6-class) | by Ernesto Jara Olveda | Medium
May 11, 2020 - How to Use Axios/Typescript like a pro! (axios-es6-class) Well today I’ll show you the way I kind of use axios with typescript. first thing is to have axios install along with typescript. npm i …