typescript enum 上的构造函数?

2022-09-03 00:56:15

目前,我们的代码有一种情况,我们在Java层中使用枚举,它存储一个id和一个“显示值”,构造函数如下:

public enum Status implements EnumIdentity {

    Active(1, "Active"),
    AwaitingReview(2, "Awaiting Review"),
    Closed(3, "Closed"),
    Complete(4, "Complete"),
    Draft(5, "Draft"),
    InProcess(6, "In Process"),
    InReview(7, "In Review"),
    NotStarted(8, "Not Started"),
    PendingResolution(9, "Pending Resolution"),
    Rejected(10, "Rejected");

    private int id;
    private String displayValue;

    PlanStatus(final int id, String displayValue) {
        this.id = id;
        this.displayValue = displayValue;
    }

    /** {@inheritDoc} */
    @Override
    public int id() {
        return id;
    }

    public String getDisplayValue() {
        return displayValue;
    }
}

我们希望typescript中的东西与此相匹配,以便以有意义的方式显示状态,以执行逻辑并在前端向用户显示值。这可能吗?有没有更好的方法来解决这个问题?我们希望避免使用诸如 status.id() = 1 或 status.name() = 'Active' 之类的逻辑,从而推动枚举。

谢谢


答案 1

Typescript 不支持扩展枚举,例如在 java 中。您可以使用类实现类似的效果:

interface EnumIdentity { }
class Status implements EnumIdentity {

    private static AllValues: { [name: string] : Status } = {};

    static readonly Active = new Status(1, "Active");
    static readonly AwaitingReview = new Status(2, "Awaiting Review");
    static readonly Closed = new Status(3, "Closed");
    static readonly Complete = new Status(4, "Complete");
    static readonly Draft = new Status(5, "Draft");
    static readonly InProcess = new Status(6, "In Process");
    static readonly InReview = new Status(7, "In Review");
    static readonly NotStarted = new Status(8, "Not Started");
    static readonly PendingResolution = new Status(9, "Pending Resolution");
    static readonly Rejected = new Status(10, "Rejected");

    private constructor(public readonly id: number, public readonly displayValue: string) {
        Status.AllValues[displayValue] = this;
    }

    public static parseEnum(data: string) : Status{
        return Status.AllValues[data];
    }

}

答案 2

推荐