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

问题描述 投票:0回答:1

我使用的库有一个如下所示的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,并希望打印'已购买')。

但是,当我做这样的事情时:

StorePurchaseStatus[1]

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

typescript enums
1个回答
1
投票

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

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

alert(StorePurchaseStatus[1]); // alreadyPurchased
alert(StorePurchaseStatus[StorePurchaseStatus[1]]);// 1
© www.soinside.com 2019 - 2024. All rights reserved.