I'm getting this error when I try to access a value inside the Enum Localization
with the variable locale
that is a string.
enum Localization {
'en-US' = '.com',
'pt-BR' = '.com.br',
'en-CA' = '.com.ca',
'en-AU' = '.com.au',
'en-IE' = '.com.ie',
'string' = 'string'
};
const locale:string = 'pt-BR' //This value will come from DB.
const result = Localization[locale];
Error:
Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'typeof Localization'. No index signature with a parameter of type 'string' was found on type 'typeof Localization'.
In Javascript works normally.
const Localization = {
'en-US': '.com',
'pt-BR': '.com.br',
'en-CA': '.com.ca',
'en-AU': '.com.au',
'en-IE': '.com.ie',
};
const locale = 'pt-BR';
console.log(Localization[locale]); // returns ".com.br"
I would like to know:
1 - How to convert the code Javascript to work in TypeScript?
2 - Why typescript is returning this error?
3 - If possible, I would like some reference links to read and understand why this error on TypeScript.
4 - What is the better approach to access data inside objects in TypeScript?
Thank you so much.