axios.get() returns an AxiosResponse<any> object, where response.data is any.

axios.get<Todo[]>() returns an AxiosResponse<Todo[]> object, where response.data is Todo[].

So you can type response as:

const response: AxiosResponse<Todo[]> = await axios.get("blabla");
Answer from rickdenhaan on Stack Overflow
🌐
Axios
axios-http.com › docs › res_schema
Response Schema | Axios Docs
// Example: `response.headers['content-type']` headers: {}, // `config` is the config that was provided to `axios` for the request config: {}, // `request` is the request that generated this response // It is the last ClientRequest instance in node.js (in redirects) // and an XMLHttpRequest instance in the browser request: {} } When using then, you will receive the response as follows: axios.get('/user/12345') .then(function (response) { console.log(response.data); console.log(response.status); console.log(response.statusText); console.log(response.headers); console.log(response.config); }); When using catch, or passing a rejection callback as second parameter of then, the response will be available through the error object as explained in the Handling Errors section.
🌐
Axios
axios-http.com › docs › api_intro
Axios API | Axios Docs
// GET request for remote image in node.js axios({ method: 'get', url: 'http://bit.ly/2mTM3nY', responseType: 'stream' }) .then(function (response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) });
Discussions

What response type should I return from Axios if I want to return response in cases where it success or fails?
Is this a TypeScript question? Do you actually need to specify the type? It should be implied. More on reddit.com
🌐 r/reactjs
6
6
July 2, 2022
how does axios handle blob vs arraybuffer as responseType?
I'm downloading a zip file with axios. For further processing, I need to get the "raw" data that has been downloaded. As far as I can see, in Javascript there are two types for this: Blobs and Arraybuffers. Both can be specified as responseType in the request options. More on stackoverflow.com
🌐 stackoverflow.com
reactjs - React and TypeScript—which types for an Axios response? - Stack Overflow
I do not understand fully how to handle Axios responses with types. More on stackoverflow.com
🌐 stackoverflow.com
How to Type Axios.js 'AxiosResponse' data generic
axios.get()? More on reddit.com
🌐 r/typescript
6
6
August 4, 2021
🌐
Reddit
reddit.com › r/reactjs › what response type should i return from axios if i want to return response in cases where it success or fails?
What response type should I return from Axios if I want to return response in cases where it success or fails? : r/reactjs
July 2, 2022 - However, you could define the interface ... start and look further into this. ... If I remember correctly, axios returns a promise. So the return type is a promise, but the return type can accept a generic....
Top answer
1 of 2
129

From axios docs:

// `responseType` indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
//   browser only: 'blob'
responseType: 'json', // default

'blob' is a "browser only" option.

So from node.js, when you set responseType: "blob", "json"will actually be used, which I guess fallbacks to "text" when no parse-able JSON data has been fetched.

Fetching binary data as text is prone to generate corrupted data. Because the text returned by Body.text() and many other APIs are USVStrings (they don't allow unpaired surrogate codepoints ) and because the response is decoded as UTF-8, some bytes from the binary file can't be mapped to characters correctly and will thus be replaced by � (U+FFDD) replacement character, with no way to get back what that data was before: your data is corrupted.

Here is a snippet explaining this, using the header of a .png file 0x89 0x50 0x4E 0x47 as an example.

(async () => {

  const url = 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png';
  // fetch as binary
  const buffer = await fetch( url ).then(resp => resp.arrayBuffer());

  const header = new Uint8Array( buffer ).slice( 0, 4 );
  console.log( 'binary header', header ); // [ 137, 80, 78, 61 ]
  console.log( 'entity encoded', entityEncode( header ) );
  // [ "U+0089", "U+0050", "U+004E", "U+0047" ]
  // You can read more about  (U+0089) character here
  // https://www.fileformat.info/info/unicode/char/0089/index.htm
  // You can see in the left table how this character in UTF-8 needs two bytes (0xC2 0x89)
  // We thus can't map this character correctly in UTF-8 from the UTF-16 codePoint,
  // it will get discarded by the parser and converted to the replacement character
  
  // read as UTF-8 
  const utf8_str = await new Blob( [ header ] ).text();
  console.log( 'read as UTF-8', utf8_str ); // "�PNG"
  // build back a binary array from that string
  const utf8_binary = [ ...utf8_str ].map( char => char.charCodeAt( 0 ) );
  console.log( 'Which is binary', utf8_binary ); // [ 65533, 80, 78, 61 ]
  console.log( 'entity encoded', entityEncode( utf8_binary ) );
  // [ "U+FFDD", "U+0050", "U+004E", "U+0047" ]
  // You can read more about character � (U+FFDD) here
  // https://www.fileformat.info/info/unicode/char/0fffd/index.htm
  //
  // P (U+0050), N (U+004E) and G (U+0047) characters are compatible between UTF-8 and UTF-16
  // For these there is no encoding lost
  // (that's how base64 encoding makes it possible to send binary data as text)
  
  // now let's see what fetching as text holds
  const fetched_as_text = await fetch( url ).then( resp => resp.text() );
  const header_as_text = fetched_as_text.slice( 0, 4 );
  console.log( 'fetched as "text"', header_as_text ); // "�PNG"
  const as_text_binary = [ ...header_as_text ].map( char => char.charCodeAt( 0 ) );
  console.log( 'Which is binary', as_text_binary ); // [ 65533, 80, 78, 61 ]
  console.log( 'entity encoded', entityEncode( as_text_binary ) );
  // [ "U+FFDD", "U+0050", "U+004E", "U+0047" ]
  // It's been read as UTF-8, we lost the first byte.
  
})();

function entityEncode( arr ) {
  return Array.from( arr ).map( val => 'U+' + toHex( val ) );
}
function toHex( num ) {
  return num.toString( 16 ).padStart(4, '0').toUpperCase();
}


There is natively no Blob object in node.js, so it makes sense axios didn't monkey-patch it just so they can return a response no-one else would be able to consume anyway.

From a browser, you'd have exactly the same responses:

function fetchAs( type ) {
  return axios( {
    method: 'get',
    url: 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png',
    responseType: type
  } );
}

function loadImage( data, type ) {
  // we can all pass them to the Blob constructor directly
  const new_blob = new Blob( [ data ], { type: 'image/jpg' } );
  // with blob: URI, the browser will try to load 'data' as-is
  const url = URL.createObjectURL( new_blob );
  
  img = document.getElementById( type + '_img' );
  img.src = url;
  return new Promise( (res, rej) => { 
    img.onload = e => res(img);
    img.onerror = rej;
  } );
}

[
  'json', // will fail
  'text', // will fail
  'arraybuffer',
  'blob'
].forEach( type =>
  fetchAs( type )
   .then( resp => loadImage( resp.data, type ) )
   .then( img => console.log( type, 'loaded' ) )
   .catch( err => console.error( type, 'failed' ) )
);
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

<figure>
  <figcaption>json</figcaption>
  <img id="json_img">
</figure>
<figure>
  <figcaption>text</figcaption>
  <img id="text_img">
</figure>
<figure>
  <figcaption>arraybuffer</figcaption>
  <img id="arraybuffer_img">
</figure>
<figure>
  <figcaption>blob</figcaption>
  <img id="blob_img">
</figure>

2 of 2
-3
Open Console/inspect window in chrome browser and paste this 


axios.get('https://images.pexels.com/photos/56866/garden-rose-red-pink-56866.jpeg?cs=srgb&dl=pexels-pixabay-56866.jpg&fm=jpg',{responseType: 'blob'})
.then(response => {
       console.log(response.data)
       window.open(URL.createObjectURL(response.data))
  }).catch(error => {
    alert("something goes wrong! Maybe image url broken, try another img url.")
})
🌐
GitHub
github.com › axios › axios
GitHub - axios/axios: Promise based HTTP client for the browser and node.js · GitHub
4 days ago - This means the last interceptor added is executed first. Response interceptors are executed in the order they were added (FIFO - First In, First Out). This means the first interceptor added is executed first.
Starred by 109K users
Forked by 11.6K users
Languages   JavaScript 86.5% | TypeScript 11.6% | HTML 1.9%
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;
Find elsewhere
🌐
Mastering JS
masteringjs.io › tutorials › axios › response-body
Get the HTTP Response Body with Axios - Mastering JS
July 23, 2020 - Axios parses the response based on the HTTP response's Content-Type header.
🌐
Tabnine
tabnine.com › home page › code › javascript › axiosrequestconfig
axios.AxiosRequestConfig.responseType JavaScript and Node.js code examples | Tabnine
/** * Relay the request to the ... = { responseType: toBuffer ? 'arraybuffer' : undefined }, axiosConfig = {}) { return axios.post(`http://${this.client.config.proxy.host}:${this.client.config.proxy.port}/`, { ...options, url }, Object.assign({ timeout: 15000, headers: { 'Content-Type': ...
🌐
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 - And TS will throw error if we try to use a non-existing key like response.data.stats. ... In TS, the error we receive in try...catch block will always have type unknown. So we won’t be able to assign type in catch instead we have to define new variable. import axios, { AxiosError, isAxiosError } from 'axios'; type PostHelloErrorType = { status: string; message: string; type: string; errors: string[]; }; async function postHello() { try { // call axios methods } catch (error) { if (isAxiosError(error)) { const err: AxiosError<PostHelloErrorType> = error; console.log(err.response.data.message); } } }
🌐
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

🌐
GitHub
github.com › axios › axios › discussions › 5674
Is it possible to change responseType handling depending on the response headers like content-encoding? · axios/axios · Discussion #5674
import stream from "stream"; import util from "util"; import axios from "axios"; const finished = util.promisify(stream.finished); axios.interceptors.response.use(async (response) => { if ( response.headers.hasContentType("application/json") && response.data instanceof stream.Readable ) { let data = ""; await finished( response.data.on("data", (chunk) => { data += chunk.toString(); }) ); response.data = data; response.config.responseType = 'json'; } return response; }); const { data, headers } = await axios.get("https://dummyjson.com/products/1", { responseType: "stream", }); console.log(headers, data);
Author   axios
🌐
ZetCode
zetcode.com › javascript › axios
Axios Tutorial - Simplifying HTTP Requests
$ node main.js { args: {}, data: '', files: {}, form: { name: 'John Doe', occupation: 'gardener' }, headers: { Accept: 'application/json, text/plain, */*', 'Content-Length': '284', 'Content-Type': 'multipart/form-data; boundary=--------------------------487292688876562281304473', Host: 'httpbin.org', 'User-Agent': 'axios/0.27.2', 'X-Amzn-Trace-Id': 'Root=1-62af1c03-32fb934410edf8130cabe019' }, json: null, ... url: 'http://httpbin.org/post' } The following example shows how to download an image with Axios. ... const axios = require('axios'); const fs = require('fs'); var config = { responseType: 'stream' }; let url = 'https://images.dog.ceo/breeds/setter-english/n02100735_4870.jpg'; async function getImage() { let resp = await axios.get(url, config); resp.data.pipe(fs.createWriteStream('image.jpg')); } getImage();
🌐
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
🌐
Medium
medium.com › @dingezzz › basic-requests-with-axios-in-typescript-5f52dea8ec9a
Basic requests with Axios in TypeScript | by Bas den Burger | Medium
January 16, 2023 - import axios from 'axios'; const api = axios.create({ baseURL: 'https://example.com/api' }); interface Response { data: any; } api.get<Response>('/users').then(response => { console.log(response.data); }); We then use the get method to make a GET request to the /users endpoint. The then method is called on the promise returned by the get method, and the callback function passed to then receives the response object. The response object contains a data property, which is typed as the Response interface defined earlier.
🌐
GitHub
github.com › axios › axios › issues › 907
responseType: 'text' return Json Object · Issue #907 · axios/axios
May 20, 2017 - // test.txt --> [false,5] axios.get('./test.txt', { responseType: 'text' }).then(response => { console.log( typeof response.data ); // output `object` , not `string`, why?
Published   May 20, 2017
Author   Airkro
🌐
DEV Community
dev.to › limacodes › why-using-axios-with-typescript-1fnj
Why using AXIOS with Typescript? - DEV Community
February 10, 2023 - Use a typed API client library such as axios-typed-isomorphic or apisauce-ts instead of the built-in fetch function when working with APIs in TypeScript. These libraries provide a more type-safe and user-friendly way of making HTTP requests and handling responses.
🌐
Mastering JS
masteringjs.io › tutorials › axios › data
Axios Response `data` Property
February 3, 2021 - Axios · Webpack · Node.js · ESLint · Mocha · Getting Started with Oso Authorization in Node.js · Here's how you can get started with Oso's authorization service in Node.js · node · Make a Sinon Spy Return a Value · Here's how to make a spy return a value in Sinon.js · sinon · Check if a File Exists in Node.js · Here's how you can check if a file exists using the fs module in Node.js · node · How to Set Response Headers in Express ·
🌐
GitHub
github.com › axios › axios › issues › 4098
Add possibility to choose response type based on the response. · Issue #4098 · axios/axios
September 28, 2021 - const config: AxiosRequestConfig = { url: '/some/example/api', method: 'GET', data: 'example_data', responseType: (response: AxiosResponse) => { if (response.status >= 200 && response.status < 300) { return 'arraybuffer' } return 'json' }, }
Author   danierlr
🌐
Upmostly
upmostly.com › home › typescript › how to use axios
How to Use Axios in Your TypeScript Apps - Upmostly
December 8, 2022 - At the moment our response has the type any. TypeScript doesn’t know what properties it has, and neither do we. Thankfully the Axios methods are generic, so let’s build some types for our response.