print
print

Reputation: 111

The element has a type "any" implicitly because the expression of type "string" cannot be used to index the type

I have a Typescript function in which I am reading the data from a JSON Object depending on the variable, but it shows me an error when accessing the property.

This is my code:

let codCountry = 'CO';

let countryId = {
    "CO": "fileIdCo",
    "ES": "fileIdEs",
    "MX": "fileIdMx"
};

let fileId;
for (let getCod of Object.keys(countryId)) {
    if (getCod == codCountry) {
        fileId = countryId[getCod] // error
    }
}

This is the error I get in countryId[getCod]:

The element has an "any" type implicitly because the expression of type "string" cannot be used to index the type "{CO: string; ES: string; MX : string;} ".
   No index signature was found with a parameter of type "string" in type "{CO: string; ES: string; MX: string;}"

Upvotes: 0

Views: 199

Answers (2)

Terry
Terry

Reputation: 66103

The problem comes from Object.keys(countryId) returning string[] instead of an array of keys available on countryId. This can be solved by casting what is returned by Object.keys() to ensure that it is an array of keys on the object, i.e.:

for (let getCod of Object.keys(countryId) as Array<keyof typeof countryId>) {
    if (getCod == codCountry) {
        fileId = countryId[getCod]
    }
}

Now you may ask, what does keyof typeof countryId actually mean?

  • typeof returns the type of the countryId object
  • keyof returns all keys available on the type of the countryId object

See proof-of-example on TypeScript Playground.


If you don't want to perform this manual casting all the time, you can even abstract that into a method that does it for you:

function getObjectKeys<T extends object>(obj: T) {
    return Object.keys(obj) as Array<keyof typeof obj>;
}

Then it's a matter of using getObjectKeys(YOUR_OBJECT) instead of using Object.keys directly:

for (let getCod of getObjectKeys(countryId)) {
    if (getCod == codCountry) {
        fileId = countryId[getCod]
    }
}

See improved example on TypeScript Playground.

Upvotes: 1

mohammad Naimi
mohammad Naimi

Reputation: 2359

define Interface

interface CC {
    CO: string;
    ES: string;
    MX: string;
}
    let cod = 'CO';

    let countryId:<CC> = {
        "CO": "fileIdCo",
        "ES": "fileIdEs",
        "MX": "fileIdMx"
    };

Upvotes: 0

Related Questions