setec
setec

Reputation: 16110

Treating typescript enum as class with list of its instances

I've often used such construction in Java:

public enum MyMartDiscountCard {
    //List of enum instances
    Progressive(3, 10, 0.01),
    FixedPercent(5, 5, 0);

    //Just like normal class with fields and 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 and want to use similar constructions in it.

As I know TS specification does't allow it. But are there any good workaround patterns to declare methods and properties and bind them to enum instance?

Upvotes: 0

Views: 241

Answers (1)

Fenton
Fenton

Reputation: 251122

I am extrapolating from your question, so this may not be the right answer for you; but I don't see why you need an enum here. You have the concept of a discount card, with specializations.

Rather than writing an enum and then having code throughout your program switching and iff-ing off of the type of card, use polymorphism so your whole program only needs to know that there is such as thing as a discount card and doesn't need to know the type at 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 to know which card they use as you put any variations on logic inside of the specializations. The DoubleFixedDiscountCard could actually just set up the super class with doubled values, but I wanted to show an example where you override the behaviour in the sub class.

Upvotes: 1

Related Questions