首页 > 解决方案 > 如果字符串与枚举成员不同,如何从枚举中获取字符串值?

问题描述

我有一个我想像对象一样解析的枚举。我真的很喜欢 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'.

标签: typescript

解决方案


我不确定枚举是否是您尝试做的最佳方法。枚举基本上为基本字典类型提供语法糖。

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();
};

推荐阅读