【问题标题】:Constructor on typescript enum?打字稿枚举的构造函数?
【发布时间】:2018-05-22 15:54:57
【问题描述】:

目前我们的代码存在这样一种情况,即我们在 Java 层中使用 Enums,它使用如下构造函数存储一个 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 中的某些内容与之匹配,以允许以有意义的方式显示状态以执行逻辑并在前端向用户显示值。 这可能吗?有没有更好的方法来处理这个?我们希望避免使用诸如 dos status.id() = 1 或 status.name() = 'Active' 这样的逻辑来推动枚举。

谢谢

【问题讨论】:

标签: java angular typescript enums ecmascript-6


【解决方案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];
    }

}

【讨论】:

  • 很遗憾,我得出了这个结论,但我认为最好将其发布到社区,以防有人找到类似的解决方法。谢谢
  • 当状态被表示为字符串?
  • 恐怕这将是手动操作。您将需要使用添加的 parseEnum 方法来转换为枚举 ..
  • 我从来没有想过怎么做,AllValues 是怎么定义的,在我身上吐出一个错误?
  • Wops.. 忘记初始化了
猜你喜欢
  • 2020-04-30
  • 2011-08-20
  • 2021-11-08
  • 1970-01-01
  • 1970-01-01
  • 2018-07-05
  • 2019-03-04
  • 1970-01-01
  • 2011-10-30
相关资源
最近更新 更多