如何在打字稿中访问枚举的名称

时间:2018-04-02 21:00:15

标签: typescript enums

我正在使用一个看起来像这样的emum的库:

/** Defines values that represent the status of a request to purchase an app or add-on. */
enum StorePurchaseStatus {
    /** The current user has already purchased the specified app or add-on. */
    alreadyPurchased = 1,
    /** The purchase request did not succeed because of a network connectivity error. */
    networkError = 3,
    /** The purchase request did not succeed. */
    notPurchased = 2,
    /** The purchase request did not succeed because of a server error returned by the Windows Store. */
    serverError = 4,
    /** The purchase request succeeded. */
    succeeded = 0,
}

我有数字值,我想打印名称(例如,我的状态为1,并且想要打印'已经购买了#39;)。

然而,当我做这样的事情时:

StorePurchaseStatus[1]

我最终得到undefined。如果我只有值?

,如何访问字符串名称

1 个答案:

答案 0 :(得分:1)

你在原帖中写的方式很好。您可以查看Playground example

以下是访问名称和值的方法:

alert(StorePurchaseStatus[1]); // alreadyPurchased
alert(StorePurchaseStatus[StorePurchaseStatus[1]]);// 1