我试图在typescript中提取数字枚举的枚举成员,但是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");
}
}
所以现在我调用GetEnumMembers方法:
ObjectUtils.GetEnumMembers(&#34; MyEnum&#34);
enumInstance结果未定义。
修改 我想用[&#34; MemberOne&#34;,&#34; MemberTwo&#34;]
返回一个字符串数组答案 0 :(得分:0)
导出的成员不会添加到window
,除非您自己添加。您可以重构代码以接受枚举本身而不是枚举名称:
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));