Utilizing Typescript for Axios Response

Incorporating Typescript into my project, I encountered a tedious issue while making an API call using axios. The problem lies within handling nested data properly.

Despite my belief that I have correctly typed everything, I persistently face a Typescript error displaying

Unsafe return on an any typed value
and
Unsafe member access .data on an any value
particularly in the line return response.data.data[0]; within my try/catch block. Can someone shed light on why my types are not functioning as expected?

export interface Source {
  curr: string;
  uuid: string;
  rate: string;
}

export interface Response {
  data: {
    data: Array<Source>;
  };
}

async function getSource({ curr, uuid, rate }: Source): Promise<AxiosResponse<Response>> {
  const requestConfig: AxiosRequestConfig = {
    method: 'get',
    url: '/url',
  };

  try {
    const response = await axios(requestConfig);
    return response.data.data[0];
  } catch (err) {
    throw new Error('error');
  }
}

Answer №1

After revising my approach, I ended up utilizing the axios.get method which resolved all issues.

export interface Parameters {
  currency: string;
  id: string;
  exchangeRate: string;
}

export interface Result {
  currency: string;
  id: string;
  exchangeRate: {
    currency: string;
    type: string;
  }
} 

async function fetchData({ currency, id, exchangeRate }: Parameters): Promise<AxiosResponse<Result>['data']> {
  try {
    const response = await axios.get<{ data: Result[] }>('/api/url');
    return response.data.data[0];
  } catch (error) {
    throw new Error('An error occurred while fetching data.');
  }
}

Answer №2

Not sure what exactly you're searching for, but this might provide some assistance. Check out this Playground link: Playground

async function getSource({ curr, uuid, rate }: Source): Promise<AxiosResponse<Response>> {
      const requestConfig: AxiosRequestConfig = {
        method: 'get',
        url: '/url',
      };
    
      try {
        const response: AxiosResponse<Response> = await axios(requestConfig); // This function expects <AxiosResponse<Response>> as the return type.
        return response;
      } catch (err) {
        throw new Error('error');
      }
    }

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

When the keyboard appears, the Ionic 2 form smoothly slides upwards

I am currently working with the most recent version of Ionic 2. In my code, I have a <ion-content padding><form></form></ion-content> containing a text input. However, when attempting to enter text on an Android device, the keyboard ...

The term 'Component' is not a valid JSX component that can be used

'Component' is causing issues as a JSX component The error appears to be within the _app.tsx file of my Next.js project. I've been struggling with this problem since yesterday, encountered it during deployment on Vercel for my Next.js TypeS ...

Develop a PDF generator in ReactJS that allows users to specify the desired file name

Is there a way to customize the file name of a generated PDF using "@react-pdf/renderer": "^2.3.0"? Currently, when I download a PDF using the toolbar, it saves with a UID as the file name (e.g., "f983dad0-eb2c-480b-b3e9-574d71ab1 ...

Using Stack and Drawer Navigations Together in React Native Navigation(v6)

I am looking to merge Stack and Drawer navigations. I have multiple screens and wish to display select screen labels in the drawer tab. <RootNavigatorStack.Navigator> <RootNavigatorStack.Screen name="DrawerTab" component={DrawerNavig ...

How can you make an IonPopover dynamically appear from a button with the perfect positioning?

I want to display a popover below a button when the button is clicked, similar to the example on the Ion docs page. However, I am having trouble implementing this in React as the code provided is only for Angular. Here is my current code: ... <IonButt ...

Troubleshooting Angular MIME problems with Microsoft Edge

I'm encountering a problem with Angular where after running ng serve and deploying on localhost, the page loads without any issues. However, when I use ng build and deploy remotely, I encounter a MIME error. Failed to load module script: Expected a ...

Can someone guide me on configuring Material-UI DataGrid in React to have multiple headers with column span?

Is there a way to achieve multiple headers with column span in the Material-UI DataGrid component? view image example ...

Angular 17 | Angular Material 17.3.1: Problem encountered with Angular Material form field focus and blur event handling

I attempted to apply (blur) and (focus) effects to my mat-form-field input field, but it seems like they are not working properly on my system. Here is a code snippet that resembles what I am using: html file <form class="example-form"> ...

"I am looking to retrieve the properties of an object that belongs to the EChartsOption type in TypeScript when working with Angular and ECharts. How

Currently, I am exploring how to access a property of an EChartOptions object in Angular 16.0.2, which may be undefined as I am still new to TypeScript. List of npm packages: eapp/src$ npm list <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Creating a merged object from a split string array in TypeScript

I possess an array containing objects structured as follows; const arr1 = [ {"name": "System.Level" }, {"name": "System.Status" }, {"name": "System.Status:*" }, {"name": "System.Status:Rejected" }, {"name": "System.Status:Updated" } ] My object ...

Potential Null Object in Typescript Mongoose: A Concern

Encountering an issue while attempting to locate my user model: Object is possibly 'null'. I would like to find a solution that does not involve suppressing TypeScript's strict rule. const { email, password } = req.body; const user = awai ...

Challenges encountered when using promises for handling mysql query results

I've been working on creating a function that will return the value of a mysql query using promises. Here's what I have so far: query(query: string): string { var response = "No response..."; var sendRequest = (query:string): Prom ...

Exploring the potential of TypeScript with native dynamic ES2020 modules, all without the need for Node.js, while also enhancing

I have a TypeScript application that utilizes es16 modules, with most being statically imported. I am now looking to incorporate a (validator) module that is only imported in debug mode. Everything seems to be functioning properly, but I am struggling to f ...

Discovering the ASP.NET Core HTTP response header in an Angular application using an HTTP interceptor

I attempted to create a straightforward app version check system by sending the current server version to the client in the HTTP header. If there's a newer version available, it should trigger a notification for the user to reload the application. Ini ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

React form submissions are not saving the state

I currently have dynamic components rendered from the server side, including a submit button component. The issue I am facing is that when I submit the form, the state reverts to its initial values instead of retaining the updated values set by child compo ...

Error encountered when extending Typography variant in TypeScript with Material UI v5: "No overload matches this call"

Currently, I am in the process of setting up a base for an application using Material UI v5 and TypeScript. My goal is to enhance the Material UI theme by adding some custom properties alongside the default ones already available. The configuration in my ...

Unable to install vue-property-decorator

When attempting to set up Vue and TypeScript with class style using vue-property-decorator, I encountered a strange script after creating the project. I was anticipating a script like this: <script lang="ts"> import {Component, Vue} from & ...

How can I extend a third-party JavaScript library in TypeScript using a declaration file?

Currently, I am working on creating a .d.ts file for an external library called nodejs-driver. While I have been able to map functions and objects successfully, I am struggling with incorporating the "inherit from objects defined in the JS library" conce ...

What is the best way to transfer the variant property of the material-ui TextField when using a higher-level React component?

I'm encountering difficulties with typing... Essentially, I have a wrapper React component for the @material-ui TextField but I am struggling with getting the typings correct for the variant property. Here's the main problem. Using @material-ui ...