Home > other >  AxiosStatic has no index signature
AxiosStatic has no index signature

Time:04-23

I'm converting a hook I recently made use of to Typescript and getting the below error

(alias) const axios: AxiosStatic
import axios
Element implicitly has an 'any' type because type 'AxiosStatic' has no index signature. Did you mean to call 'axios.get'?ts(7052)

Which is spawning from the below code.

const fetchData = async () => {
    axios[method](url, data, config)
        .then((res) => {
            setResponse(res.data);
        })
        .catch((err) => {
            setError(err);
        })
        .finally(() => {
            setloading(false);
        });
};

I believe specifically it's related to axios[method]

I was using this previously so I could pass in various request types dynamically. I'm unsure of how to resolve the above error using best typescript practices.

These values are retrieved from the following in the following

({ url, method, data })

P.S: I'm aware that there might be other issues in the snippet but I'll resovle those as they're just related to types.

CodePudding user response:

It is complaining because method could potentially be any string and not a key of axios. You can fix this by making its type a key of axios.

First a union of all methods axios supports:

type Methods = "head" | "options" | "put" | "post" | "patch" | "delete" | "get";

Then if this is a function we can make the parameter type Methods:

function foo(method: Methods) {
    axios[method] // works
    // ...
}

Or if it's a variable:

let method: Method = ...;

You may need to use a cast too:

let method = ... as Method;

Playground

  • Related