Jason Addleman
Jason Addleman

Reputation: 719

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

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

Upvotes: 39

Views: 20669

Answers (2)

MikuZZ
MikuZZ

Reputation: 101

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.

Upvotes: 5

thoughtrepo
thoughtrepo

Reputation: 8383

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;

Upvotes: 62

Related Questions