【发布时间】: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应该像这样扩展AxiosResponse:export interface ISearchServiceResponse extends AxiosResponse { data: Filters[] }
标签: javascript typescript types