[英]How to convert string-enum to enum in Reactjs typescript?
I have an enum like this in a .ts
file:我在.ts
文件中有一个这样的枚举:
export enum TimeOfDay{
MORNING = "AM",
NOON = "12noon",
EVENING = "PM",
MIDNIGHT = "12midnight"
}
In another .tsx
file, I have a string "12noon"
in a variable named selectedOption
and I want to convert it into this enum.在另一个.tsx
文件中,我在一个名为selectedOption
的变量中有一个字符串"12noon"
,我想将它转换成这个枚举。 How can I do that?我怎样才能做到这一点?
I tried these based on the other answers in StackOverflow, but none of the worked:我根据 StackOverflow 中的其他答案尝试了这些,但都没有奏效:
var timeInDay: TimeOfDay = TimeOfDay[selectedOption];
The above is giving TS7053
error.以上给出了TS7053
错误。
var timeInDay: TimeOfDay = <TimeOfDay>selectedOption;
The above is giving TS17008
and TS2604
errors.以上给出了TS17008
和TS2604
错误。
var timeInDay: TimeOfDay = (<any>TimeOfDay)[selectedOption];
The above is giving TS2339
and TS17008
errors.以上给出了TS2339
和TS17008
错误。
I've gone through many answers on this site but didn't find a solution.我已经在这个网站上浏览了很多答案,但没有找到解决方案。
Here are some ways to use a string
where a string enum type is expected:以下是在需要字符串枚举类型的情况下使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.