何时将 AxiosResponse 与 Typescript 结合使用

时间:2021-05-16 02:01:28

标签: typescript axios

我有一个关于在 Typescript 中使用轴的问题。我有一个执行异步调用的函数(点击免费的 NASA API)。

import axios, { AxiosResponse } from 'axios'; 

interface Camera {
    id: number, 
    name: string, 
    rover_id: number, 
    full_name: string
};

interface Rover {
    id: number, 
    name: string, 
    landing_date: string,
    launch_date: string, 
    status: string, 
}


interface Photo {
    id: number,
    sol: number,
    camera: Camera,
    img_src: string,
    earth_date: string,
    rover: Rover
};

interface Response {
    photo: Photo[]
};


const getData = async (): Promise<AxiosResponse> => {
    return await axios.get<Response>('https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=DEMO_KEY')
}

这是正确的吗?如果我这样做

const getData = async (): Promise<Response>

打字稿不高兴了。此函数是否不返回返回客户 Response 对象的承诺?

什么时候应该使用 AxiosResponse,什么时候应该使用自定义界面?

1 个答案:

答案 0 :(得分:0)

我们必须读取 AxiosResponse.data 字段才能获取响应数据

public async getData() : Promise<Response>  {
    const response = await axios.get('https://api.nasa.gov/mars-photos/api/v1/rovers/curiosity/photos?sol=1000&api_key=DEMO_KEY');
    return response.data; 
} 
相关问题