Axios与TypeScript配合使用的正确方法

uoifb46i  于 2022-12-18  发布在  iOS
关注(0)|答案(2)|浏览(162)

我的应用程序中出现了一个似乎无法解决的错误。我将axiosTypeScript一起使用。下面是我尝试执行的代码示例:

export const fetchTransactions = (PageNum: number, PageSize: number, Context_id: number) => new Promise<Transaction[]> (async (resolve, reject) => {

  try
  {
    const response = await axios.post<AxiosResponse<Transaction[]>>(FETCH_TRANSACTIONS_URL, {PageNum, PageSize, Context_id})
    const {transactions} = response.data
    resolve(transactions)
  }
  catch (error) {
    reject(error.response);
  }
})

现在我得到的const {transactions} = response.data的错误如下:

我怎样才能删除这个错误?正确的响应类型应该是什么?

zwghvu4y

zwghvu4y1#

通常,我这样使用axios和Typescript

const fetchTransactions = (PageNum: number, PageSize: number, Context_id: number): Promise<Transaction[]> =>
  axios
    .post<Transaction[]>(FETCH_TRANSACTIONS_URL, {PageNum, PageSize, Context_id})
    .then((response) => {
      if (response.status >= 200 && response.status < 300) {
        return response.data;
      }
      throw new Error(response.status.toString());
    })
    .catch(({ response }) => {
      throw new Error(response.status);
    });
7cwmlq89

7cwmlq892#

我不想在Typescript中输入这个非常大的JSON结构,所以我使用AxiosPromise,它工作了:

export class MyComponent {
  public sales: any;

  constructor() {
    const response = await axios.get<AxiosPromise>( base_api_url + '/sales')
    console.log(response.data);
    this.sales = response.data;
  }
}

}

相关问题