Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign Enum to variable?

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.

like image 477
scipper Avatar asked Aug 25 '26 13:08

scipper


1 Answers

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;
}
like image 119
Matt McCutchen Avatar answered Aug 27 '26 04:08

Matt McCutchen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!