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
Enums or enumerations are a new data type supported in TypeScript. Most object-oriented languages like Java and C# use enums. This is now available in TypeScript too. In simple words, enums allow us to declare a set of named constants i.e. a collection of related values that can be numeric or string values.
Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.
The class or constructor cannot be static in TypeScript.
An enum is usually selected specifically because it is immutable - i.e. you would never want the values to change as it would make your application unpredictable.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With