我得到了一个通用类,其中一个通用参数是一个枚举。可以基于通用参数获取枚举的键吗?
一个简化的示例:
abstract class Foo<T> {
protected abstract myEnumValues: T[];
getEnumKeys() {
// Can I get the string representation of the keys of T here?
// I can get them from MyEnum
console.log(Object.keys(MyEnum)
.filter(isNaN));
// And I can use T's keys for typing
let x: {
[keys in keyof T]: any
};
}
}
enum MyEnum {
KeyA = 1,
KeyB = 2,
KeyC = 3
}
class Bar extends Foo<MyEnum> {
protected myEnumValues: MyEnum[] = [MyEnum.KeyA, MyEnum.KeyB];
}
const bar = new Bar();
bar.getEnumKeys();
答案 0 :(得分:1)
否,您不能,在编译时没有类型信息可用。但是,您可以将枚举对象传递给该类,因此它将在运行时可用,例如:
abstract class Foo<T> {
protected abstract myEnumValues: ReadonlyArray<T[keyof T]>;
constructor(private readonly enumObj: T) {}
getEnumKeys(): ReadonlyArray<keyof T> {
return Object
.keys(this.enumObj)
.filter(key => isNaN(Number(key)))
.map(key => key as keyof T);
}
}
enum MyEnum {
KeyA = 1,
KeyB = 2,
KeyC = 3
}
class Bar extends Foo<typeof MyEnum> {
protected myEnumValues = [MyEnum.KeyA, MyEnum.KeyB];
constructor() {
super(MyEnum);
}
}
const bar = new Bar();
答案 1 :(得分:0)
否,通用参数仅在编译时可用以进行类型检查。 但是要解决您的问题,您可以将枚举传递给基类,并从该类型中读取信息。