Can you set a static enum inside of a TypeScript c

2019-03-17 14:15发布

问题:

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 to TypeScript, so I'm not sure of the correct syntax for this, but below is some pseudo-code (which extends a Backbone Model) I'd like to be able to use to achieve what I need...

class UnitModel extends Backbone.Model {
    static enum UNIT_STATUS {
        NOT_STARTED,
        STARTED,
        COMPLETED
    }

    defaults(): UnitInterface {
        return {
            status: UNIT_STATUS.NOT_STARTED
        };
    }


    isComplete(){
        return this.get("status") === UNIT_STATUS.COMPLETED;
    }

    complete(){
        this.set("status", UNIT_STATUS.COMPLETED);
    }
}

export = UnitModel;

I need to be able to reference the enum inside of this class, but I also need to be able to reference the enum outside of the class, like the following:

import UnitModel = require('path/to/UnitModel');
alert(UnitModel.UNIT_STATUS.NOT_STARTED);//expected to see 0 since enums start at 0

回答1:

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;