Static typing of the Axios request methods

In my utility method I make use of the Axios request methods as follows:

const response = await axios[method](url, body);

where the arguments conform with an interface

import { Method } from 'axios';

interface UseRequestProps {
  url: string;
  method: Lowercase<Method>;
  body: any;
}

Though the method argument gets narrowed down to

UseRequestProps.method: "get" | "delete" | "head" | "options" | "post" | "put" | "patch" | "purge" | "link" | "unlink"

I’m still getting an error of

TS7052: Element implicitly has an any type because type AxiosStatic has no index signature. Did you mean to call axios.get

that doesn’t happen when I define the method argument as a union type with fewer request types:

interface UseRequestProps {
  url: string;
  method: "get" | "delete" | "head" | "options" | "post" | "put" | "patch";
  body: any;
}

What’s the difference between the two variations? How do I get the first version to work?

The methods "purge" | "link" | "unlink" weren’t on the Axios request types.
The solution was to intersect the Method and the Axios request types with

interface UseRequestProps {
  ...
  method: Lowercase<Method> & keyof typeof axios;
  ...
}

Leave a Comment