I want to get language from localHost and use it in translation pipe like this:
transform(value: string): string {...
localStorage.setItem("language", JSON.stringify("en"));
let language = JSON.parse(localStorage.getItem("language") ?? "en");
language = language as keyof typeof translates[number];
const translates: {
key: string;
cz: string;
en: string;
}[]
let returnTranslate = "";
translates.forEach((item) => {
if (item["key"] === value) {
returnTranslate = item[language];
}
});
But I get this error:
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ key: string; cz: string; en: string; }'
In this part of code:
item[language]
CodePudding user response:
The TS compiler is not happy because you are trying to index with a type that is implicitly any.
But why is your language variable implicitly any? It comes from the first assignment
let language = JSON.parse(localStorage.getItem("language") ?? "en");
// language is of type any here
using as here
language = language as keyof typeof translates[number];
temporarily lets the TS compiler know that you are forcing the type here, but then you use your language variable (which is of type any) as an index later in the code and the TS compiler does not like that.
So instead, you would have to use as where you actually use language as the index
returnTranslate = item[language as keyof typeof translates[number]];
But because that is verbose and you know that your language should be a keyof typeof translates[number] all the time, you can just do it right at the beginning.
let language = JSON.parse(localStorage.getItem("language") ?? "en") as keyof typeof translates[number];
With this change you also get rid of the line language = language as keyof typeof translates[number];.
