3

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.

dveloso
  • 84
  • 1
  • 5
  • 1
    I ran your example on a few online ts editors, but they all ran okay. Can you share your config file? – yosefc Sep 01 '20 at 21:08
  • It's working with typescript: https://stackblitz.com/edit/typescript-39eczb?file=index.ts – Prawin soni Sep 01 '20 at 21:08
  • https://stackoverflow.com/questions/50417254/dynamically-access-enum-in-typescript-by-key – Abhirup Pal Sep 01 '20 at 21:13
  • Hey guys, thank you so much for helping me, to get the error you need to add a type to the `locale` variable like `const locale: string = 'pt-BR'` I updated the example. Please try to run now. – dveloso Sep 02 '20 at 08:24

2 Answers2

6

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

John B
  • 1,129
  • 14
  • 23
1

For something like this, I'd recommend making a key type for ease of use and to ensure type checking continues to work down the chain.

enum Localization {
  'en-US' = '.com',
  'pt-BR' = '.com.br',
  'en-CA' = '.com.ca',
  'en-AU' = '.com.au',
  'en-IE' = '.com.ie',
  'string' = 'string'
};

type LocalizationKey = keyof typeof Localization;
const locale:LocalizationKey = 'pt-BR' //This value will come from DB.
const result = Localization[locale];


// TYPECHECKING TEST:
function localization(r: Localization) {
  console.log(r)
}

localization(result);

// @ts-expect-error this line should error because it's not a key of Localization
localization('fail');
Keegan Brown
  • 515
  • 3
  • 5