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

Angular 6: Sending Back HTTP Headers

I have been working on a small Angular Application for educational purposes, where I am utilizing a .net core WebApi to interact with data. One question that has come up involves the consistent use of headers in all Post and Put requests: const headers = ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

react-vimeo not firing onPause and onPlay events

I am facing an issue with triggering props when playing a Vimeo video on my webpage. Here's a snippet of my code: import Vimeo from '@u-wave/react-vimeo'; const handleVimeoProgress = (data: any) => { console.log('Progress:' ...

The data type 'StaticImageData' cannot be converted to type 'string'

I've hit a roadblock with interfaces while working on my NextJS and TypeScript project. I thought I had everything figured out, but I'm encountering an issue with the src prop in my Header component. The error messages I keep receiving are: Typ ...

What steps can be taken to address an undefined error before the execution of useEffect?

Today I encountered a small issue with my online player. It's fetching songs from the database using useEffect and saving them in state like this: const [songs, setSongs] = useState([]); const [currentSong, setCurrentSong] = useState(songs[0]); a ...

Is there a way to loop through objects in Angular 2

I am working with an Array of Objects named comments, and my goal is to select only the ones that have a specific post id and copy them to another array of objects. The issue I am facing is finding a way to duplicate the object once it has been identified. ...

When using expressjs and typescript, you may encounter an error stating that the type 'typeof <express.Router>' cannot be assigned to the parameter type 'RequestHandlerParams'

Working on my project using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped. I've set up a router and want to access it from a subpath as per the official 4.x documentat ...

Issue with rendering the search component due to a conflict with validate.js

I am currently facing an issue with my search component that includes validation using JavaScript. The problem I am encountering is that when I first focus on the input, the validation and request do not work. However, after losing focus on the input, cli ...

I'm looking for a way to create a Redux thunk action creator that will return a promise. How

In my code, I have a primary thunk that is triggered by a button click. Within this thunk, I need to invoke another thunk and ensure it completes before proceeding. The second thunk returns a promise. Below is an excerpt of the code in question: export f ...

Laravel Sanctum - Access Denied post login

My current project is a small web app developed using Laravel 8 sanctum and Vue. I have set up everything on both my local environment and the production server using Docker, ensuring consistency. The application is running smoothly on a subdomain called s ...

Is there a way to incorporate new members into a pre-existing type in TypeScript?

While examining the definition file for the commander project, one can observe the following interface being utilized: interface IExportedCommand extends ICommand { Command: commander.ICommandStatic; Option: commander.IOptionStatic; [key: stri ...

combine string inputs when ng-click is triggered

Is there a way to pass a concatenated string using ng-click to MyFunction(param: string)? I have tried but so far, no luck: <input id="MeasurementValue_{{sample.Number}}_{{$index}}" ng-click="Vm.MyFunction('MeasurementValue_{{sample.Number ...

Tips for effectively utilizing Mongoose models within Next.js

Currently, I am in the process of developing a Next.js application using TypeScript and MongoDB/Mongoose. Lately, I encountered an issue related to Mongoose models where they were attempting to overwrite the Model every time it was utilized. Here is the c ...

Surprising fraction of behavior

Looking for some clarification on the types used in this code snippet: interface UserDTO { id: string; email: string; } const input: Partial<UserDTO> = {}; const userDTO: Partial<UserDTO> = { id: "", ...input }; const email = us ...

Harness the power of TypeScript in a single test file with jest's expect.extend() method

This question is similar to Can you limit the scope of a TypeScript global type? but it presents a slightly different scenario that requires clarification (although an answer to this would be greatly appreciated as well). In my Jest setup, I am attempting ...

Using dangerouslySetInnerHTML in ReactJS can potentially strip away data attributes

After adding a data-test attribute to the a anchor tag within an HTML string and inserting it using dangerouslySetInnerHTML, I noticed that the data attributes are somehow being stripped out. Is there a way to prevent this from happening? These attribute ...

Dealing with server-side errors while utilizing react-query and formik

This login page utilizes formik and I am encountering some issues: const handleLogin = () => { const login = useLoginMutation(); return ( <div> <Formik initialValues={{ email: "", password: "" }} ...

Extending Vue components with TypeScript for enhanced styling features

Exploring Vuejs with TypeScript components has been an educational journey for me. While I found using class-based components quite intuitive, I've encountered errors when trying to use the Vue.extend({}) approach. Are there any resources such as arti ...

Custom type checker that validates whether all properties of a generic object are not null or undefined

In an attempt to create a user-defined type guard function for a specific use-case, I am faced with a challenge: There are over 100 TypeScript functions, each requiring an options object. These functions utilize only certain properties from the object wh ...

Tips for integrating tsconfig with webpack's provide plugin

In my project, I have a simple component that utilizes styled-components and references theme colors from my utils.tsx file. To avoid including React and styled-components in every component file, I load them through WebpackProvidePlugin. Everything works ...