Home > Back-end >  TypeScript with redux-thunk and axios
TypeScript with redux-thunk and axios

Time:10-05

I am trying to convert my app to TypeScript and I've come to the last part where I need to refactor ApiClient file which just handles API requests.

Here is a simplified version:

import axios from "axios";
import * as types from "../types/types"
import * as routes from "../constants/ApiRoutes"

// axios.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";
// axios.defaults.headers.common["Accept"] = "application/json";

const apiClient = {
  getComments: function (callback: Function) {
    return axios
      .get(routes.GET_COMMENTS_URL)
      .then((response) => response.data)
      .then(callback) // this throws an error
      .catch((err) => console.log(err));
  },

};

export default apiClient;


// this is the code in action creators

export function fetchCommentsAction(callback: Function) {
  return function (dispatch: Function) {
    apiClient.getComments((comments: types.Comment[]) => {
      dispatch(commentsReceivedSuccess(comments));
    });
    if (callback) {
      callback();
    }
  };
}

Callback function runs when the response is received from the server but the problem is that if I put callback to be type Function I get an error saying Argument of type 'Function' is not assignable to parameter of type '(value: never) => PromiseLike<never>'.

What would be a quick fix for this?

Thank you!

CodePudding user response:

I don't think you should ever use "Function", it's too abstract. You can type a function with "() => void" instead, where void is the return type.

So in your case I would try something like:

getComments: function (callback: (value: any) => Promise<any>) {

Also the compiler tells you to try (value: never) => PromiseLike<never>, I would try that first.

Here is a link to the documentation on typing callbacks: https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html#return-types-of-callbacks

Ideally, you should type the response object your request is returning and you should avoid to use never or any..

  • Related