TypeScript:尝试访问枚举时没有带有“字符串”类型参数的索引签名

dve*_*oso 3 javascript typescript reactjs

当我尝试使用字符串Enum Localization变量访问内部的值时,出现此错误。locale

enum Localization {
    'en-US' = '.com',
    'pt-BR' = '.com.br',
    'en-CA' = '.com.ca',
    'en-AU' = '.com.au',
    'en-IE' = '.com.ie',
    'string' = 'string'
};
Run Code Online (Sandbox Code Playgroud)
 const locale:string = 'pt-BR' //This value will come from DB.
 const result = Localization[locale];
Run Code Online (Sandbox Code Playgroud)

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

错误索引打字稿

在 Javascript 中工作正常。

     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"
Run Code Online (Sandbox Code Playgroud)

我想知道:

1 - 如何将 Javascript 代码转换为在 TypeScript 中工作?
2 - 为什么打字稿返回此错误?
3 - 如果可能的话,我想要一些参考链接来阅读并理解为什么 TypeScript 上会出现此错误。
4 - 在 TypeScript 中访问对象内部数据的更好方法是什么?

太感谢了。

Joh*_*n B 7

下面的代码至少适用于地图类型,我认为它没有理由不适用于显式枚举类型。 const result = Localization[locale as keyof typeof Localization];

来源reddit