【问题标题】:What is the type of enum object枚举对象的类型是什么
【发布时间】:2018-10-10 11:23:34
【问题描述】:

我想写一个枚举的一组元素的包装类。

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 会根据构造函数中的规范推断类型)

【问题讨论】:

    标签: typescript generics typing


    【解决方案1】:

    你可以切换类型参数来表示枚举容器对象而不是枚举。枚举类型为ENUMERATION[keyof ENUMERATION]&gt;

    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
    {
    
    }
    

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2018-10-13
    • 1970-01-01
    • 2010-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多