Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript: No index signature with a parameter of type 'string' when try to access the Enum

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'.

error index typescript

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.

like image 259
dveloso Avatar asked Oct 17 '25 15:10

dveloso


1 Answers

The below works at least with a map type, I see no reason why it wouldnt work with an explict enum type. const result = Localization[locale as keyof typeof Localization];

Source reddit

like image 84
John B Avatar answered Oct 19 '25 04:10

John B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!