带有 Axios 响应的 Typescript

pro*_*h3t 3 typescript axios

在使用 Typescript 进行 API 调用时axios遇到了嵌套数据场景。

尽管我相信它的输入正确,但我不断收到 Typescript 错误,指出Unsafe return on an any typed value我的. 有人可以澄清为什么我的类型没有像我“认为”的那样工作吗?Unsafe member access .data on an any valuereturn response.data.data[0];try/catch

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');
  }
}
Run Code Online (Sandbox Code Playgroud)

pro*_*h3t 5

经过一些返工后,我开始使用axios.get并能够解决所有问题。

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');
  }
}
Run Code Online (Sandbox Code Playgroud)