1

Let's say we have an enum like the following:

export enum HeroActionEnum {
  STRIKE = 'strike',
  HIDE = 'hide',
  RUN = 'fly',
  TACKLE = 'tackle',
}

now we create a new class with attributes which have the exact same keys represented in the HeroActionEnum.

export class Hero {
  [HeroActionEnum.STRIKE]: EventEmitter<void>;
  [HeroActionEnum.HIDE]: EventEmitter<void>;
  [HeroActionEnum.RUN]: EventEmitter<void>;
  [HeroActionEnum.TACKLE]: EventEmitter<void>;
  ...
}

The DRY principle is not happy about this. I would actually like to sum the keys up like:

export class Hero {
  [key in HeroActionEnum]: EventEmitter<void>;
  ...
}

I tried a lot but I got nothing to work so far. Thanks in advance for your help!

sevic
  • 879
  • 11
  • 36
  • yeah, I tried something similar in the past, do you have tried use an object instead an enum? just a guess – David Nithael Torres Lima Aug 14 '20 at 10:07
  • @DavidNithaelTorresLima yes i already tried a `const allHeroActions = [ 'strike', 'hide', ...]` but also without success. – sevic Aug 14 '20 at 10:20
  • [Maybe this can help?](https://stackoverflow.com/a/52700831/14097137) – David Nithael Torres Lima Aug 14 '20 at 10:25
  • Unfortunately not the question :/ `let hero: { [key: HeroActionEnum]: EvenEmitter}` works without a problem. but no idea how to implement this into a class. – sevic Aug 14 '20 at 10:37
  • 1
    What about `abstract class AbstractHero { actions: { [key: HeroActionEnum]: EventEmitter }}`? – r3dst0rm Aug 17 '20 at 11:40
  • Not exactly the same, but yes this resolves the issue as well and is the solution i went with thanks! :) still would be interesting if there is a way to assign class attributes by an enum but i don't think so. – sevic Aug 17 '20 at 16:26

0 Answers0