typescript - 如果字符串与枚举成员不同,如何从枚举中获取字符串值?
问题描述
我有一个我想像对象一样解析的枚举。我真的很喜欢 Swift 编程语言如何使用 .rawValue 来获取枚举成员的字符串值,(i.e. HelloWorld.one.rawValue = "this is one")
但我无法弄清楚如何在 Typescript 中执行此操作。
enum HelloWorld {
one = "this is one",
two = "two",
three = "the third"
}
const getStringFromEnum = (num: HelloWorld) => {
return HelloWorld[num]
};
如果我输入HelloWorld.one
到 getSringFromEnum 函数,我想输出“这是一个”,但我得到的错误是Property '[HelloWorld.one]' does not exist on type 'typeof HelloWorld'.
解决方案
我不确定枚举是否是您尝试做的最佳方法。枚举基本上为基本字典类型提供语法糖。
enum HelloWorld {
one = "this is one",
two = "two",
three = "the third"
}
转换成类似的东西
const HelloWorld {
one: "this is one",
two: "two",
three: "the third",
"this is one": "one",
two = "two",
"the third": "three"
}
允许轻松地来回查找其键和值。不需要getStringFromEnum
函数,您可以HelloWorld.one
从导入枚举的任何地方简单地使用。
如果您需要查找函数,但不需要向后查找,则使用变量而不是枚举可能会更好
const helloWorld = {
one: "this is one",
two: "two",
three: "the third"
}
function getStringFromEnum(num: keyof typeof helloWorld): string {
return helloWorld[num];
};
当然 helloWorld 可以预先输入,无需typeof helloWorld
. 否则,你是对的。你可以使用
function getStringFromEnum(num: HelloWorld): string {
return num.valueOf();
};
推荐阅读
- python-3.x - 如何在 Python3 中将日志记录与多处理一起使用
- windows - 损坏的包管理器?找不到模块提供程序 (PowerShellGet)
- azure - 获取 Azure Log Analytics 免费层
- html - 使Div中的图像不调整大小
- r - 在 UI 出现后延迟加载 Shiny 中的库,但在实际需要之前
- python - 如何查找文件中有多少个相同的单词?
- c++ - 在 C++ 中格式化文本文件
- python - 从对象列表中提取特定属性列表
- visual-studio - 如何通过 USB 与应用程序/程序通信
- android - Android 画布点击不可用