Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 951
Jason Addleman Avatar asked Sep 10 '15 18:09

Jason Addleman


People also ask

Can we define enum inside a class TypeScript?

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.

Does TypeScript support enum?

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.

Does TypeScript support static classes?

The class or constructor cannot be static in TypeScript.

Can we change enum values 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.


1 Answers

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; 
like image 132
thoughtrepo Avatar answered Sep 20 '22 11:09

thoughtrepo