I'm using react and typescript and am getting this error on the last line of the code block below.
Element implicitly has an 'any' type because expression of type 'number' can't be used to index type '{}'. No index signature with a parameter of type 'number' was found on type '{}'. ts(7053)
from the line hemisphereInfo[hemisphere][country] = countryInfo;
(see below for full code). It has an issue with the [country]
bit.
Basically, I'm trying to add an unknown key pair to an object that's typed with an interface.
export interface IHemisphere {
[key: string]: object
north: {
[key: string]: object
};
south: {
[key: string]: object
};
}
const hemisphereInfo: IHemisphere = {
north: {},
south: {},
};
for (const hemisphere in hemisphereInfo) {
const countriesInHemisphere: string[] = this.hemiAPI(hemisphere) as unknown as string[];
for (const country in countriesInHemisphere) {
const countryInfo = this.countryAPI(country);
hemisphereInfo[hemisphere][country] = countryInfo;
}
}
Firstly, country
is a string, not a number like it says in the error message. Secondly, I've seen examples solving this problem with strongly typed keys, but I won't know what they keys will be when they come in, so I can't specify each one in the interface.