With TypeScript, you have the flexibility to specify any data type in the generic types when using the axios.get method

axios.get('/api')

When working with TypeScript as shown above, it is important to designate types for better clarity. This allows us to reference the type definition of axios, like so:

(method) AxiosInstance.get<any, AxiosResponse<any>>(url: string, config?: AxiosRequestConfig | undefined): Promise<AxiosResponse<any>>
                           ^^^ <- ???

I am puzzled by the use of any in the first generic type of the get method AxiosInstance.get<any,. What is the purpose of using this any type?

Answer №1

Make sure to check out the axios type definitions.

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

The initial type argument is what the api returns. By default, this is set to any.

The second one represents the response type and defaults to a response that includes the type of the first argument.

Answer №2

When working with Axios type generics, the first argument specifically refers to the data property within the response object. However, if you also utilize the second argument, it encompasses the entire response object, which includes data as well as config, headers, status, and statusText. Additionally, there exists a third parameter that impacts the request parameters, illustrated in the examples below:

import { Axios, AxiosResponse } from 'axios';

type MyStatus = 200 | 404
type MyResponseData = { test: string, total: number }
type MyRequestData = { page: number }

interface CustomResponse extends AxiosResponse {
  status: MyStatus;
  // You can customize response data here if needed
}

(new Axios('/')).get<
  MyResponseData,
  CustomResponse,
  MyRequestData,
>('/test',
  // The typing aligns with MyRequestData
  { data: {page: 1} }
// The types of res correspond to MyResponseData
// and res.data has CustomResponse types
).then(res => {
  // typeof res.data = MyResponseData
  // typeof res.status = MyStatus
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a Next.js application that retrieves mock data and dynamically presents it on the user interface

I've been attempting to retrieve some placeholder data from an API and showcase it on the screen, but unfortunately nothing is appearing. Interestingly, the data does show up in the console, just not on the actual screen. function Shop() { const [pr ...

What is the best way to call upon a necessary module from various files?

When working with Node.js, I am using Socket.io in my main.js file like this: const io = require('socket.io')(http); Additionally, I have a separate "sub" file called api.js where I delegate some of my business logic. To include this file, I us ...

Tips for displaying an HTML page using JavaScript

In my project, I am working with an .html file (File X) that needs to immediately open another .html file (File Y) based on a certain value. Could someone provide guidance on the best way to achieve this using JavaScript? Additionally, I would like the pa ...

Is there a way to prevent the letters from moving when I hover over them?

What occurs when the numbers are hovered over: https://gyazo.com/20b6426d435551c5ee238241d3f96b4d Whenever I hover over the pagination numbers, they shift to the right, and I am unsure of what mistake I made in my code that's causing this. Below, I ...

JavaScript struggles to obtain the timezone information when Daylight Saving Time is

Can someone help me with setting a user's timezone offset for PHP through ajax? When a page is loaded with session data, if there is no pre-existing data, the following script is inserted into the page: <script type="text/javascript"> $(doc ...

Using Jquery to extract URL parameters

Can anyone suggest a jQuery function I can use to fetch URL parameters? I've been utilizing the following function, which works well; however, it encounters issues when the URL doesn't have any parameters. I would like it to return an empty stri ...

JQuery enthusiast seeks cheerful clicker for callback upon event binding

Incorporating a complex functionality into a click event is proving to be challenging $(someSelector)).bind('click', someFunction(a,b,c)); function somefunction(a,b,c) { return function() { // dive into complexity $(anotherS ...

Dynamic styles object for React components with inline styles

I have a styles object let styles = { step_div:{ height:'150px', } } I'm trying to display multiple div elements with different colors using React class Layout extends React.Component{ constructor(props) { super(props); ...

Is there a way to send the image object to the onclick function as it is being assigned?

I apologize if my question is a bit unclear, as I am currently teaching myself how to use javascript. I am working on generating image thumbnails dynamically and would like the ability for users to enlarge the image when they click on the thumbnails. The p ...

delivering axios response to display the page

I have a code snippet that requests data from an external API using axios and I want to incorporate the response into my rendered page. Here is my code: //Snippet from my controller required in main routes exports.recordBySlug = async (req, res, next) =&g ...

Error: The last line is missing a trailing comma

I'm struggling to understand why my tslint insists on having a trailing comma at the end of the last line in the objects. Is there a way to configure the ignore rule for the last line of objects? Appreciate any help! For example: settings = { ...

Upon loading the page, include a class to a specific element within an AngularJS ng-repeat function by evaluating the content of a JSON object

I have a group of buttons that are generated from a json object. Whenever a user clicks on a button, it changes color (referred to as the selected color) using the ng-class directive with bootstrap classes. If the same button is clicked again, it reverts b ...

NextJS API Generator for OpenAPI specifications

In my NextJS project, we utilize the /api path to implement our API, with an openapi.yaml file defining the interface. To generate the API client successfully, we run the following command: openapi-generator-cli generate -i data/api/openapi.yaml -o src/api ...

Javascript - Unable to update button text

I am encountering a problem with updating the text of a Bootstrap button when a collapsed element is opened or closed. The icon part is updating successfully, but I am struggling to get the button text to update and I cannot figure out why. My knowledge o ...

JavaScript Enigma: Instantiate 2 Date variables with identical values, yet they ultimately display distinct dates on the calendar

I need some help understanding something in my screenshot. Although both tmpStart and itemDate have been assigned the same numeric value, they display different calendar dates. start = 1490683782833 -> tmpStart = "Sun Mar 26 2017 16:51:55 GMT+ ...

Adding information to an Excel spreadsheet using JavaScript

I'm facing a challenge in appending data to an existing Excel file using node.js. I've tried using the xlsx-writestream package with the code snippet below: var XLSXWriter = require('xlsx-writestream'); var writer = new XLSXWriter(&a ...

Utilizing the jQuery index for organizing JSON keys

Recently, I came across an interesting issue with a jQuery event handler in my code. When clicked, this specific event creates a JavaScript object based on a list of favorite links: $('#saveFavorites').on('click', function(){ a ...

Having trouble with the locality function in Google Places v3 API autocomplete?

After successfully using the code below for about a week, I returned to work on it and found that it was no longer functioning properly. My goal is to only display localities. According to Google's documentation, "locality" is the correct option for a ...

The current date object in JavaScript will only display the year or a combination of the month and

$scope.articles = [ { link: "http://google.com", source: "Google", title: "hello", "date": new Date(2008, 4, 15) }, ]; <tbody> <tr ng-repeat = "article in articles | orderBy:sortType:sortReverse | filter:searchArticle ...

"Utilizing Promises in AngularJS Factories for Synchronous API Calls

Attempting to implement synchronous calls using a factory pattern. $scope.doLogin = function (username, password, rememberme) { appKeyService.makeCall().then(function (data) { // data = JSON.stringify(data); debugAlert("logi ...