将TypeScript枚举的键分配给变量

时间:2020-04-04 17:01:47

标签: typescript enums

我有以下字符串枚举:

export enum ReportGraphTypes {
    OverallGraph = "Long description...",
    OverallByDateGraph = "....",
    MilageGraph = "....",
    FuelPricesGraph = "....",
    FuelConsumptionGraph = "...."
}

然后我将枚举映射到选择字段,并使用枚举键作为值。 我想将默认值传递给我的选择字段,并且始终可以执行以下操作:
let selected = "OverallGraph";,但已硬编码。
我也尝试过:
let selected = ReportGraphTypes[ReportGraphTypes.OverallGraph];,但出现以下错误:
Element implicitly has an 'any' type because expression of type 'ReportGraphTypes.FuelPricesGraph' can't be used to index type 'typeof ReportGraphTypes'.
将该键分配给变量的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

也许尝试使用keyof typeof运算符来获取密钥?我通常使用与第二种解决方案相同的方法,到目前为止,我自己还没有遇到任何问题。可能是因为该方法仅适用于number类型值。但是也许您可以改用map对象。