您可以在 TypeScript 类中设置静态枚举吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32509056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you set a static enum inside of a TypeScript class?
提问by Jason Addleman
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...
我想以某种方式能够在我的 TypeScript 类上静态设置一个枚举,并能够通过导出类在内部和外部引用它。我是 TypeScript 的新手,所以我不确定正确的语法,但下面是一些伪代码(它扩展了一个主干模型)我希望能够用来实现我需要的。 ..
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
回答by thoughtrepo
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;