1

So I have the following code using axios library:

const BTrustURLResponse: Response = await axios.get(`${process.env.BTRUST_URL}/flow/${process.env.BTRUST_FLOWID}/link?callback_url=${callback_url}`, {
    headers: {
        'Authorization': `Bearer ${process.env.BTRUST_API_KEY}`,
    },
});

I know for sure (console.log(Object.keys(BTrustURLResponse))) that the returned object has property data. But as default Response interface does not include data property.

How can I fix it?

I've tried the following:

  1. Created @types directory, with response directory, then: enter image description here

And this is the file itself:

 declare global {
    export interface Response {
        data?: string,
    }
}
  1. Then I did in tsconfig.json the following:"typeRoots": ["@types", "./node_modules/@types"]

But still I could not use .data with the Response.

shalvi muqta
  • 153
  • 1
  • 3
  • 16
  • Does this answer your question? [how to use a type for the response from axios.get](https://stackoverflow.com/questions/57629111/how-to-use-a-type-for-the-response-from-axios-get) – eol Feb 01 '21 at 12:39

2 Answers2

2

You don't have to create a separate @types file for creating a Response interface. Axios has a generic interface named AxiosResponse<T> which takes the T generic variable from get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;.. Then that T generic var is used for data property of the AxiosResponse

see this:

interface ResponseData{
  _id?: string
  //... or any "property" you wanna add
}

const BTrustURLResponse = await axios.get<RespnseData>(`${process.env.BTRUST_URL}/flow/${process.env.BTRUST_FLOWID}/link?callback_url=${callback_url}`, {
    headers: {
        'Authorization': `Bearer ${process.env.BTRUST_API_KEY}`,
    },
});

Hope it works...

KR Tirtho
  • 447
  • 5
  • 13
0

From https://github.com/axios/axios documentation looks like data: {} is an object but you are using string as the type for data object. data?: string, This could be an issue. If you don't know the structure of your response then as a starting can use data?: any , if that works then you can give a proper type of your data object.

web2dev
  • 557
  • 10
  • 28