I just declare an interface and use a variable of that type access the enum. Keeping the interface and enum in sync is actually easy, since TypeScript complains if something changes in the enum, like so.
error TS2345: Argument of type 'typeof EAbFlagEnum' is not assignable
to parameter of type 'IAbFlagEnum'. Property 'Move' is missing in type
'typeof EAbFlagEnum'.
The advantage of this method is no type casting is required in order to use the enum (interface) in various situations, and more types of situations are thus supported, such as the switch/case.
// Declare a TypeScript enum using unique string
// (per hack mentioned by zjc0816)
enum EAbFlagEnum {
None = <any> "none",
Select = <any> "sel",
Move = <any> "mov",
Edit = <any> "edit",
Sort = <any> "sort",
Clone = <any> "clone"
}
// Create an interface that shadows the enum
// and asserts that members are a type of any
interface IAbFlagEnum {
None: any;
Select: any;
Move: any;
Edit: any;
Sort: any;
Clone: any;
}
// Export a variable of type interface that points to the enum
export var AbFlagEnum: IAbFlagEnum = EAbFlagEnum;
Using the variable, rather than the enum, produces the desired results.
var strVal: string = AbFlagEnum.Edit;
switch (strVal) {
case AbFlagEnum.Edit:
break;
case AbFlagEnum.Move:
break;
case AbFlagEnum.Clone
}
Flags were another necessity for me, so I created an NPM module that adds to this example, and includes tests.
https://github.com/djabraham/ts-enum-tools