Andrea Costanzo
Andrea Costanzo

Reputation: 2215

Specify axios response data type

I'm building the API to connect my react app with my backend service and I want to use typescript to specify the type of data inside my Axios request. How can I update the type of data inside Axios response without modifying the other fields (see getAllProjects in the code below)?

class MyApi {
   constructor(token: string | null) {
     let headers: any = {
            'Content-Type': 'application/json',
     };
     if (token) {
        headers = {
          ...headers, //append other basic proprieties
          'Authorization': 'Token ' + token
        }
     }

     this.baseEndpoint = axios.create({
        baseURL: `${baseURL}`,
        headers: headers
     });

  }

  //DATA
  const getAllProjects = async () : Promise<AxiosResponse<?????>> => this.baseEndpoint.get('/projects/');
}

Simply assigning the desired type (suppose data: string[] for this example) throws the following error:

Argument of type 'string[]' is not assignable to parameter of type 'SetStateAction<never[]>'.
  Type 'string[]' is not assignable to type 'never[]'.
    Type 'string' is not assignable to type 'never'.

Upvotes: 4

Views: 22087

Answers (1)

Arman Charan
Arman Charan

Reputation: 5797

Try

export const getAllProjects = async () => backend.get<string[]>('/projects/')

For additional context, Axios requests are typed as the following:

request<T = any, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R>

Where an AxiosResponse is defined as being

export interface AxiosResponse<T = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: any;
  config: AxiosRequestConfig;
  request?: any;
}

This allows them to take a generic type parameter that can be used to specify the type of the data property of a given response, like so:

type Data = {
  A: string
  B: number
  C: boolean
  // Etc.
}

Axios.get<Data>(endpoint).then(response => {
  const { data } = response // Data
  data.a // string
  data.b // number
  data.c // boolean
})

Upvotes: 13

Related Questions