将typescript枚举视为具有实例列表的类

将typescript枚举视为具有实例列表的类,typescript,Typescript,我经常在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 i

我经常在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);
    }
}
现在我正在学习Typescript,希望在其中使用类似的结构


我知道TS规范不允许这样做。但是,有没有什么好的变通模式来声明方法和属性并将它们绑定到enum实例?

我是根据您的问题推断出来的,因此这可能不是您的正确答案;但我不明白您为什么需要这里的
enum
。你有折扣卡的概念,有专门化

与其写一个枚举,然后在整个程序中使用代码切换和关闭卡片类型,不如使用多态性,这样整个程序只需要知道有折扣卡之类的东西,而根本不需要知道类型

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; 
    }
}

DiscountCard
的消费者不需要知道他们使用的是哪一张卡,因为您在专业化内部的逻辑上有任何变化。实际上,
DoubleFixedDiscountCard
可以用两倍的值设置超类,但是我想展示一个例子,在这个例子中,您可以覆盖子类中的行为。

是的,我认为这是个好主意。我太执着于把所有东西都放在一个地方,就像Enum一样。无论如何,我可以将所有这些派生类放入枚举中,只是为了结构。