Can you set a static enum inside of a TypeScript class?

前端 未结 2 1406
无人共我
无人共我 2021-02-03 22:57

I\'d like to somehow be able to statically set an enum on my TypeScript class and be able to reference it both internally and externally via exporting the class. I\'m fairly new

相关标签:
2条回答
  • 2021-02-03 23:21

    You can declare a namespace right after your class, and declare the enum inside the namespace. For example:

    class UnitModel extends Backbone.Model {
        defaults(): UnitInterface {
            return {
                status: UNIT_STATUS.NOT_STARTED
            };
        }
    
    
        isComplete(){
            return this.get("status") === UNIT_STATUS.COMPLETED;
        }
    
        complete(){
            this.set("status", UNIT_STATUS.COMPLETED);
        }
    }
    
    namespace UnitModel {
        export enum UNIT_STATUS {
            NOT_STARTED,
            STARTED,
            COMPLETED
        }
    }
    
    export = UnitModel;
    

    Then you can use UnitModel.UNIT_STSTUS to reference you enum.

    0 讨论(0)
  • 2021-02-03 23:25

    To do this, you would need to define it outside of the class first, then assign it as a static property.

    enum UNIT_STATUS {
        NOT_STARTED,
        STARTED,
        COMPLETED,
    }
    
    class UnitModel extends Backbone.Model {
    
        static UNIT_STATUS = UNIT_STATUS;
    
        isComplete(){
            return this.get("status") === UNIT_STATUS.COMPLETED;
        }
    }
    
    export = UnitModel;
    
    0 讨论(0)
提交回复
热议问题