代码之家  ›  专栏  ›  技术社区  ›  DannyD

如何访问typescript中的枚举名称

  •  0
  • DannyD  · 技术社区  · 8 年前

    我正在使用一个具有如下所示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,想打印“alreadyPurchased”)。

    然而,当我这样做时:

    StorePurchaseStatus[1]
    

    我最终得到 undefined 。如果我只有值,如何访问字符串名称?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Patrick Desjardins    8 年前

    你在原始帖子中的写作方式很好。你可以检查这个 Playground example

    以下是如何访问名称和值:

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