Treating typescript enum as class with list of its instances -


i've used such construction in java:

public enum mymartdiscountcard {     //list of enum instances     progressive(3, 10, 0.01),     fixedpercent(5, 5, 0);      //just normal class fields , methods     private int initial;     private int max;     private int ratio;     public mymartdiscountcard(int initial, int max, float ratio){...}     public calculatediscount(float totalspent){          return math.max(initial + totalspent*ratio, max);     } } 

now i'm learning typescript , want use similar constructions in it.

as know ts specification does't allow it. there workaround patterns declare methods , properties , bind them enum instance?

i extrapolating question, may not right answer you; don't see why need enum here. have concept of discount card, specializations.

rather writing enum , having code throughout program switching , iff-ing off of type of card, use polymorphism whole program needs know there such thing discount card , doesn't need know type @ all.

class discountcard {     constructor(private initial: number, private max: number, private ratio: number){      }      public calculatediscount(totalspent: number) {          return math.max(this.initial + totalspent * this.ratio, this.max);     } }  class progressivediscountcard extends discountcard {     constructor() {         super(3, 10, 0.01);     } }  class fixedpercentdiscountcard extends discountcard {     constructor() {         super(5, 5, 0);     } }  class doublefixeddiscountcard extends discountcard {     constructor() {         super(5, 5, 0);     }      public calculatediscount(totalspent: number){         var normalpoints = super.calculatediscount(totalspent);          return normalpoints * 2;      } } 

consumers of discountcard don't need know card use put variations on logic inside of specializations. doublefixeddiscountcard set super class doubled values, wanted show example override behaviour in sub class.


Comments