我在TypeScript中定义了以下enum:
enum Color{
Red, Green
}
现在在我的函数中,我以字符串的形式接收颜色。我尝试了以下代码:
var green= "Green";
var color : Color = <Color>green; // Error: can't convert string to enum
如何将该值转换为enum?
我在TypeScript中定义了以下enum:
enum Color{
Red, Green
}
现在在我的函数中,我以字符串的形式接收颜色。我尝试了以下代码:
var green= "Green";
var color : Color = <Color>green; // Error: can't convert string to enum
如何将该值转换为enum?
当前回答
如果你正在处理TypeScript 4.1+和字符串enum,并且你想要一个简单的具有编译时和运行时安全的字符串到enum转换器,下面的工作很好:
export const asEnum = <
T extends { [key: string]: string },
K extends keyof T & string
>(
enumObject: T,
value: `${T[K]}`
): T[K] => {
if (Object.values(enumObject).includes(value)) {
return (value as unknown) as T[K];
} else {
throw new Error('Value provided was not found in Enum');
}
};
enum Test {
hey = 'HEY',
}
const test1 = asEnum(Test, 'HEY'); // no complaints here
const test2 = asEnum(Test, 'HE'); // compile-time error
const test3 = asEnum(Test, 'HE' as any); // run-time error
其他回答
如果你正在处理TypeScript 4.1+和字符串enum,并且你想要一个简单的具有编译时和运行时安全的字符串到enum转换器,下面的工作很好:
export const asEnum = <
T extends { [key: string]: string },
K extends keyof T & string
>(
enumObject: T,
value: `${T[K]}`
): T[K] => {
if (Object.values(enumObject).includes(value)) {
return (value as unknown) as T[K];
} else {
throw new Error('Value provided was not found in Enum');
}
};
enum Test {
hey = 'HEY',
}
const test1 = asEnum(Test, 'HEY'); // no complaints here
const test2 = asEnum(Test, 'HE'); // compile-time error
const test3 = asEnum(Test, 'HE' as any); // run-time error
TS 3.9.x
var color : Color = Color[green as unknown as keyof typeof Color];
它在TypeScript 4.4.3 TS游乐场链接中为我工作。
const stringToEnumValue = <T extends Record<string, string>, 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
];
enum Color {
Red = 'red',
Green = 'green',
}
const result1 = stringToEnumValue(Color, 'yellow'); // undefined
const result2 = stringToEnumValue(Color, 'green'); // Color.Green
console.log(result1) // undefined = undefined
console.log(result2) // Color.Green = "green"
对于Typescript >= 4,此代码工作:
enum Color{
Red, Green
}
// Conversion :
var green= "Green";
var color : Color = green as unknown as Color;
我得到了它的工作使用以下代码。
var green= "Green";
var color : Color= <Color>Color[green];