我想编写一个枚举元素集的包装器类。
export class Flags<ENUMERATION> {
items = new Set<ENUMERATION>();
enu; // what type ?
constructor(enu) { // what type ?
this.enu=enu;
}
set(id:ENUMERATION) { this.items.add(id); return this; }
// an use: an arbitrary string references an enum element or is rejected
setChecking(id:string):boolean{
if (id in this.enu){
let what = this.enu[id];
this.items.add(what);
return true;
}
return false;
}
// .....
}
如此
enum Props{ One, Two, Three };
let fls=new U.Flags<Props>(Props);
fls.set(Props.One);
fls.set("asdf"); // ts detectes the wrong value
fls.set(Props.Two);
if (!fls.setChecking("xxxx")) // Some external string can be checked agains the set/enum
throw or whatever
我的问题是属性enu和构造函数中的参数的类型是什么,枚举对象的类型是什么?
在我可以编写的构造函数中指定类型:
let fls=new U.Flags(Props);
(ts会根据构造函数中的规范推断类型)
答案 0 :(得分:1)
您可以切换type参数来表示枚举容器对象而不是枚举。枚举的类型为ENUMERATION[keyof ENUMERATION]>
export class Flags<ENUMERATION extends { [P in keyof ENUMERATION]: any}> {
items = new Set<ENUMERATION[keyof ENUMERATION]>();
enu: ENUMERATION; // what type ?
constructor(enu: ENUMERATION) { // what type ?
this.enu=enu;
}
set(id:ENUMERATION[keyof ENUMERATION]) { this.items.add(id); return this; }
// an use: an arbitrary string references an enum element or is rejected
setChecking(id:string):boolean{
if (id in this.enu){
let what = this.enu[id as keyof ENUMERATION];
this.items.add(what);
return true;
}
return false;
}
// .....
}
enum Props{ One, Two, Three };
let fls=new Flags(Props);
fls.set(Props.One);
fls.set("asdf"); // ts detectes the wrong value
fls.set(Props.Two);
if (!fls.setChecking("xxxx")) // Some external string can be checked agains the set/enum
{
}