【问题标题】:Typescript Error with Axios API response - array methods do not exist on responseAxios API 响应的 Typescript 错误 - 响应中不存在数组方法
【发布时间】:2022-01-18 21:13:12
【问题描述】:

我遇到了 axios 响应和打字稿错误的问题 - 我得到的错误是“ISearchServiceResponse”类型上不存在属性“过滤器”。

我如何告诉 typescript 我要使用的对象是一个数组,而不是从服务器返回后的 axios 响应?

  useEffect(() => {
    if (apiKey) {
      const getUserFilters = async () => {
        try {
          const res = await searchService.filters.get(apiKey)
        
          const responsesWithoutKeywordAsset = res.data
            .filter(item => !item.key.includes('BAR'))
            .filter(other => !other.key.includes('FOO')) 

        } catch (err) {
          console.error(err)
        }
      }
      getUserFilters()
    }
  }, [apiKey])



type Res<T> = Promise<AxiosResponse<T>>

export const searchService = {
  filters: {
    get: (apiKey: string): Res<SearchService.ISearchServiceResponse> =>
    axiosInstance.get(
        www.myapicall.com?aggregation=PAYLOAD_CATEGORY`,
        {
          headers: {
            'X-Api-Key': apiKey
          }
        })
  }

}

export namespace SearchService {
    export interface ISearchServiceResponse {
      data: Filters[]
     }
     export interface Filters {
        key:string
        value: string
      }
    
  }
  

【问题讨论】:

  • Property 'filter' does not exist on type 'ISearchServiceResponse' 表示'ISearchServiceResponse' 不是数组,所以你不必告诉打字稿,你需要传递正确的数据,我们不知道'ISearchServiceResponse' 是什么样子像这样我们无能为力。
  • 您是否从 axios 导入了 AxiosResponse 类型?很确定ISearchServiceResponse 应该像这样扩展AxiosResponseexport interface ISearchServiceResponse extends AxiosResponse { data: Filters[] }

标签: javascript typescript types


【解决方案1】:

一般建议

我个人从未直接使用AxiosResponse 定义我的接口。 相反,我使用了 Axios 类型中的泛型方法。

例如:

const response = axios.get<User[]>("/users");

在这种情况下,响应的类型为AxiosResponse&lt;User[]&gt;。 这意味着response.data 有一个User[] 类型,它将有一个filter 函数。

您的具体问题

如果我很好地阅读了您的代码,那么Res&lt;SearchService.ISearchServiceResponse&gt; 等于Promise&lt;AxiosResponse&lt;SearchService.ISearchServiceResponse&gt;&gt;。 如果你解开承诺,那么你会得到AxiosResponse&lt;SearchService.ISearchServiceResponse&gt;

这意味着AxiosResponse 有一个data 类型为SearchService.ISearchServiceResponse 的字段。 这个data,也有一个由你的界面定义的data字段。

所以调用response.data.data.filter 就可以了。
但我会把界面改成更有意义的东西。

来自cmets的建议

在 cmets 中建议(@marita-farruggia)让 ISearchServiceResponseAxiosResponse 扩展,这将起作用。

但是,我将其定义如下:

interface ISearchServiceResponse extends AxiosResponse<Filters[]> {}

注意:然后您需要将Res&lt;T&gt; 的定义更改为Promise&lt;T&gt;(在我看来,这使得Res 类型成为Promise 的不必要抽象)。

【讨论】:

    猜你喜欢
    • 2021-02-21
    • 2021-06-30
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多