如何在 Reactjs 打字稿中将字符串枚举转换为枚举?
How to convert string-enum to enum in Reactjs typescript?
我在 .ts
文件中有一个这样的枚举:
export enum TimeOfDay{
MORNING = "AM",
NOON = "12noon",
EVENING = "PM",
MIDNIGHT = "12midnight"
}
在另一个 .tsx
文件中,我在一个名为 selectedOption
的变量中有一个字符串 "12noon"
,我想将它转换成这个枚举。我该怎么做?
我根据 Whosebug 中的其他答案尝试了这些,但是 none 的工作:
var timeInDay: TimeOfDay = TimeOfDay[selectedOption];
以上给出 TS7053
错误。
var timeInDay: TimeOfDay = <TimeOfDay>selectedOption;
以上给出 TS17008
和 TS2604
错误。
var timeInDay: TimeOfDay = (<any>TimeOfDay)[selectedOption];
以上给出 TS2339
和 TS17008
错误。
我在这个网站上浏览了很多答案,但没有找到解决方案。
这里有一些使用 string
的方法,其中需要字符串枚举类型:
enum TimeOfDay{
MORNING = "AM",
NOON = "12noon",
EVENING = "PM",
MIDNIGHT = "12midnight"
}
function doSomethingWithTimeOfDay (time: TimeOfDay): void {
console.log(time);
}
const selectedOption = '12noon';
// As you observed, this doesn't work:
doSomethingWithTimeOfDay(selectedOption);
// ~~~~~~~~~~~~~~
// Argument of type '"12noon"' is not assignable to parameter of type 'TimeOfDay'.
// Use a predicate to check at runtime:
function isTimeOfDay (value: string): value is TimeOfDay {
return Object.values(TimeOfDay).includes(value as TimeOfDay);
}
if (isTimeOfDay(selectedOption)) {
doSomethingWithTimeOfDay(selectedOption); // ok
}
// Or, if you're certain that the string is a valid string enum value,
// then you can use an assertion:
doSomethingWithTimeOfDay(selectedOption as TimeOfDay); // ok
我在 .ts
文件中有一个这样的枚举:
export enum TimeOfDay{
MORNING = "AM",
NOON = "12noon",
EVENING = "PM",
MIDNIGHT = "12midnight"
}
在另一个 .tsx
文件中,我在一个名为 selectedOption
的变量中有一个字符串 "12noon"
,我想将它转换成这个枚举。我该怎么做?
我根据 Whosebug 中的其他答案尝试了这些,但是 none 的工作:
var timeInDay: TimeOfDay = TimeOfDay[selectedOption];
以上给出 TS7053
错误。
var timeInDay: TimeOfDay = <TimeOfDay>selectedOption;
以上给出 TS17008
和 TS2604
错误。
var timeInDay: TimeOfDay = (<any>TimeOfDay)[selectedOption];
以上给出 TS2339
和 TS17008
错误。
我在这个网站上浏览了很多答案,但没有找到解决方案。
这里有一些使用 string
的方法,其中需要字符串枚举类型:
enum TimeOfDay{
MORNING = "AM",
NOON = "12noon",
EVENING = "PM",
MIDNIGHT = "12midnight"
}
function doSomethingWithTimeOfDay (time: TimeOfDay): void {
console.log(time);
}
const selectedOption = '12noon';
// As you observed, this doesn't work:
doSomethingWithTimeOfDay(selectedOption);
// ~~~~~~~~~~~~~~
// Argument of type '"12noon"' is not assignable to parameter of type 'TimeOfDay'.
// Use a predicate to check at runtime:
function isTimeOfDay (value: string): value is TimeOfDay {
return Object.values(TimeOfDay).includes(value as TimeOfDay);
}
if (isTimeOfDay(selectedOption)) {
doSomethingWithTimeOfDay(selectedOption); // ok
}
// Or, if you're certain that the string is a valid string enum value,
// then you can use an assertion:
doSomethingWithTimeOfDay(selectedOption as TimeOfDay); // ok