我正在寻找可以从string 获得enum 的答案,但在我的情况下,枚举值具有不同的字符串值对应项。 OP 有一个简单的 Color 枚举,但我有一些不同的东西:
enum Gender {
Male = 'Male',
Female = 'Female',
Other = 'Other',
CantTell = "Can't tell"
}
当您尝试使用 "Can't tell" 字符串解析 Gender.CantTell 时,它会返回带有原始答案的 undefined。
另一个答案
基本上,我想出了另一个答案,受到this answer 的强烈启发:
export const stringToEnumValue = <ET, T>(enumObj: ET, str: string): T =>
(enumObj as any)[Object.keys(enumObj).filter(k => (enumObj as any)[k] === str)[0]];
注意事项
- 我们采用
filter 的第一个结果,假设客户端从枚举中传递了一个有效字符串。如果不是这样,undefined 将被返回。
- 我们将
enumObj 转换为any,因为使用TypeScript 3.0+(当前使用TypeScript 3.5),enumObj 被解析为unknown。
使用示例
const cantTellStr = "Can't tell";
const cantTellEnumValue = stringToEnumValue<typeof Gender, Gender>(Gender, cantTellStr);
console.log(cantTellEnumValue); // Can't tell
注意:正如有人在评论中指出的那样,我还想使用noImplicitAny。
更新版本
没有转换为any 和正确的类型。
export const stringToEnumValue = <T, K extends keyof T>(enumObj: T, value: string): T[keyof T] | undefined =>
enumObj[Object.keys(enumObj).filter((k) => enumObj[k as K].toString() === value)[0] as keyof typeof enumObj];
此外,更新后的版本调用方式更简单,可读性更强:
stringToEnumValue(Gender, "Can't tell");