在 TypeScript 中,要从字符串中获取枚举类型,可以使用以下步骤:
enum Color {
Red = "red",
Green = "green",
Blue = "blue"
}
getEnumValue
:function getEnumValue(str: string): Color | undefined {
const keys = Object.keys(Color).filter(key => isNaN(Number(key)));
const values = keys.map(key => Color[key as keyof typeof Color]);
const index = values.indexOf(str);
return index !== -1 ? Color[keys[index] as keyof typeof Color] : undefined;
}
const colorValue = getEnumValue("red");
console.log(colorValue); // 输出:Color.Red
这样,我们就可以从 TypeScript 中的字符串中获取枚举类型了。
推荐的腾讯云相关产品:无
参考链接:
领取专属 10元无门槛券
手把手带您无忧上云