typescriptclassenums

Use typescript enum values as class properties


I have a typescript enum MyEnum:

export enum MyEnum {
  ALPHA = 'ALPHA',
  BETA = 'BETA'
}

I want to use the enum values as properties of another class. I know can do stuff like that:

export class MyClass {
  vals: {[key in MyEnum]} = {
    ALPHA: true,
    BETA: false
  }

  anotherProp: boolean;
  
  aMethod() {
    if (this.vals.ALPHA) doStuff();
  }
}

But I'm wondering if it's possible to use the enum values as properties of the class itself, not as properties of one of its nested objects:

export class myClass {
  // here be my properties from myEnum. How?

  anotherProp: boolean
  
  aMethod() {
    if (this.ALPHA) doStuff(); // ALPHA is type checked
  }
}

Is that possible?


Solution

  • You can merge an interface into the class:

    https://www.typescriptlang.org/docs/handbook/declaration-merging.html

    I use this pattern a lot:

    Playground

    enum MyEnum {
      ALPHA = 'ALPHA',
      BETA = 'BETA'
    }
    
    type BoolFlags = {[key in MyEnum]: boolean};
    interface MyClass extends BoolFlags {};
    class MyClass {
      
      constructor(){
        for(const key in MyEnum){
          this[(MyEnum as any)[key] as MyEnum] = false; // this could be done better, but not related to the question
        }
      }
    
      log() {
        if (this.ALPHA) console.log('ALPHA is', this.ALPHA);
      }
    }
    
    const a = new MyClass;
    console.log(a.ALPHA, a.BETA);
    a.ALPHA = true;
    a.log();