Typescript Axios types in return

Viewed 623

I have an axios post that does this

public myFunc(auth: string) {
    return axios.post(`${auth_provider_base_url}/access`, {
        code: auth
    }).then((resp) => resp.data);
}

Which returns a hash (I suppose)

but can I return it as an interface?

interface Iface {
    field: string;
}

public myFunc(auth: string): IFace {
    return axios.post(`${auth_provider_base_url}/access`, {
        code: auth
    }).then((resp) => resp.data);
}

Or do I even want to?

1 Answers

Yes, you could simply set the type in the post function like this axios.post<Iface>(...) and it will return this type AxiosResponse<Iface> Here is how could be using your code:

interface Iface {
    field: string;
}

public async myFunc(auth: string): Promise<Iface> {
    const axiosResponse = await axios.post<Iface>(`${auth_provider_base_url}/access`, {
        code: auth
    });
    return axiosResponse.data;
}

However, in this way you are only interested in the data from the request, you are ignoring some other properties that you will find in the axiosResponse

As a side note, I modified your function to use async/await, it could help you on better error handling, but that is up to you.

Related