5

Working with Typescript while making an API call with axios and have come across a nested data scenario.

Although I believe to have it typed correctly, I keep receiving a Typescript error stating Unsafe return on an any typed value and Unsafe member access .data on an any value for the return response.data.data[0]; line of my try/catch. Can someone provide some clarity around why my types aren't working as I "think" they are?

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');
  }
}
1
  • 1
    axios(requestConfig) returns AxiosPromise<any>, so response.data is of type any. Commented May 5, 2021 at 15:19

2 Answers 2

6

After some re-work, I landed on using axios.get and was able to get it all worked out.

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

export interface Response {
  curr: string;
  uuid: string;
  rate: {
    curr: string;
    type: string;
  }
} 

async function getSource({ curr, uuid, rate }: Args): Promise<AxiosResponse<Response>['data']> {
  try {
    const response = await axios.get<{ data: Response[] }>('/url');
    return response.data.data[0];
  } catch (err) {
    throw new Error('error');
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Don't know what exactly you are looking for but this might help you. 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); //funtion expects <AxiosResponse<Response>> as return.
        return response;
      } catch (err) {
        throw new Error('error');
      }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.