你可以在TypeScript类中设置一个静态枚举吗? [英] Can you set a static enum inside of a TypeScript class?

查看:947
本文介绍了你可以在TypeScript类中设置一个静态枚举吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以某种方式能够静态设置一个枚举在我的TypeScript类,并能够通过导出类在内部和外部引用它。我对TypeScript相当新,所以我不确定这个的正确语法,但下面是一些伪代码(它扩展了一个骨干模型)我想能够使用来实现我需要的。 ..

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


推荐答案

要做到这一点,你需要首先在类之外定义它,然后将它作为一个静态属性。

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;

这篇关于你可以在TypeScript类中设置一个静态枚举吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆