在使用 axios
进行 API 调用时使用 Typescript,并且遇到了嵌套数据场景。
虽然我相信它的输入是正确的,但我一直收到一个 Typescript 错误,指出 Unsafe return on an any typed value
的 Unsafe member access .data on an any value
行的 return 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');
}
}
答案 0 :(得分:1)
经过一些返工,我开始使用 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');
}
}
答案 1 :(得分:0)
不知道您在寻找什么,但这可能对您有所帮助。游乐场链接: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');
}
}