The title says it all: how do I assign an Enum to a local variable like:
export enum MyEnum {
TOP = "top",
RIGHT = "right",
BOTTOM = "bottom",
LEFT = "left"
};
const myEnum: MyEnum = MyEnum; // <-Error: Type 'typeof MyEnum' is not assignable to type 'MyEnum'.
Link here.
In order someone wonders why I would do that: I want to iterate over the Enum values in my AngularJs template:
// component controller
export class MyClass {
public myEnum: MyEnum;
constructor() {
this.myEnum = MyEnum;
}
}
// component template
<ul>
<li ng-repeat="enum in $ctrl.myEnum">{{ enum }}</li>
</ul>
EDIT
I know that I could assign every single value like:
constructor() {
this.myEnum = {};
this.myEnum.TOP = MyEnum.TOP;
this.myEnum.RIGHT= MyEnum.RIGHT;
this.myEnum.BOTTOM= MyEnum.BOTTOM;
this.myEnum.LEFT= MyEnum.LEFT;
}
But this is not what I want. Not handy, very error prone.
You can use typeof MyEnum to refer to the type of the entire enum namespace as opposed to the type of an enum member:
export class MyClass {
public myEnum: typeof MyEnum;
constructor() {
this.myEnum = MyEnum;
}
}
But it might be easier to use a property initializer so TypeScript will infer the type and you don't have to use a type annotation at all:
export class MyClass {
public myEnum = MyEnum;
}
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