简体   繁体   English

如何使用打字稿通过名称将枚举作为变量引用

[英]how to reference an enum via its name as variable using typescript

For example I want to extract an object array from an Enum definition. 例如,我想从枚举定义中提取对象数组。

Object.keys(HelloWorldEnum).map(el => {
  return {
    label: HelloWorldEnum[el],
    value: el
  };
});


enum HelloWorldEnum {
  option1 = 'Option1',
  option2 = 'Option2',
  option3 = 'Option3'
}

Now, how I can do with a function that passing 'HelloWorld' as a variable, below is not work: 现在,如何使用将“ HelloWorld”作为变量传递的函数不起作用:

getOptions(str) {
    return Object.keys([str + 'Enum']).map(el => {
      return {
        label: [str + 'Enum'][el],
        value: el
      };
    });
  }

Even I changed to window[str + 'Enum'] , or this[str + 'Enum'] that it won't works since the Enum definition is not existing in neither window nor this namespace 甚至我更改为window[str + 'Enum']this[str + 'Enum'] ,因为Enum定义既不存在于窗口中也不存在于此命名空间中,所以它不起作用

Assume the above code is in any of an Angular Component 假设以上代码在任何Angular组件中

Typescript will ultimately transpile your enum definition to something that looks like: Typescript最终会将您的枚举定义转换为如下形式:

var HelloWorldEnum = {};
HelloWorldEnum["option1"] = "Option1";
HelloWorldEnum["option2"] = "Option2";
HelloWorldEnum["option3"] = "Option3";

As you can see. 如你看到的。 It's just a variable name in local scope. 它只是本地范围内的变量名。 It's not added to the global window object or any other object. 它不会添加到全局窗口对象或任何其他对象。

There is only one way to access a variable by it's name in javascript and it's not recommended... and that's by using eval() which is considered a dangerous api which can cause performance issues in your javascript engine just by using it. 只有一种方法可以通过javascript中的变量名来访问变量,因此建议使用...,那就是使用eval() ,这被认为是一种危险的api,仅通过使用它就可能在JavaScript引擎中导致性能问题。

Warnings aside. 除了警告。 Here is how one might do what you ask. 这是您可能会做的事情。

 var HelloWorldEnum = {}; HelloWorldEnum["option1"] = "Option1"; HelloWorldEnum["option2"] = "Option2"; HelloWorldEnum["option3"] = "Option3"; function getVariableFromScope(variable) { return eval(variable); } function getOptions(name) { const _enum = getVariableFromScope(`${name}Enum`); return Object.keys(_enum).map(el => ({ label: _enum[el], value: el })); }; console.log(getOptions('HelloWorld')); 

Ultimately, I think you should explore other ways of solving the underlying issue. 最终,我认为您应该探索解决根本问题的其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM