简体   繁体   English

在Typescript中按字符串创建枚举实例

[英]Create enum instance by string in Typescript

I am trying to extract the enum members of a numeric enum in typescript, but window[name] does return an undefined object. 我试图在打字稿中提取数字枚举的枚举成员,但window [name]确实返回了未定义的对象。

export enum MyEnum {    
  MemberOne = 0,   
  MemberTwo = 1
}

export class ObjectUtils {
  public static GetEnumMembers(name: string): Array<string> {
    let enumInstance = window[name];

    return Object.keys(enumInstance).map((k: any) => enumInstance[k]).filter((x: any) => typeof (x) == "string");
  }
}

So now I call the GetEnumMembers method like this: 所以现在我这样调用GetEnumMembers方法:

ObjectUtils.GetEnumMembers("MyEnum"); ObjectUtils.GetEnumMembers( “MyEnum”);

enumInstance results undefined. enumInstance结果未定义。

edit: I want to return a string array with ["MemberOne", "MemberTwo"] 编辑:我想用[“ MemberOne”,“ MemberTwo”]返回一个字符串数组

Exported members won't be added to window unless you add them yourself. 除非您自己添加导出的成员,否则不会将其添加到window You can refactor your code to accept the enum itself instead of the enum name: 您可以重构代码以接受枚举本身而不是枚举名称:

export enum MyEnum {    
  MemberOne = 0,   
  MemberTwo = 1
}

// Some other file
import { MyEnum } from "./MyEnum"

class ObjectUtils {
  public static GetEnumMembers(e: {
    [key: string]: any
  }): Array<string> {
    return Object.keys(e).map((k: any) => e[k]).filter((x: any) => typeof (x) == "string");
  }
}

// And use it like:
console.log(ObjectUtils.GetEnumMembers(MyEnum));

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

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