我在.ts檔案中有一個這樣的列舉:
export enum TimeOfDay{
MORNING = "AM",
NOON = "12noon",
EVENING = "PM",
MIDNIGHT = "12midnight"
}
在另一個檔案中,我在一個名為的變數中.tsx有一個字串,我想將它轉換為這個列舉。我怎樣才能做到這一點?"12noon"selectedOption
我根據 StackOverflow 中的其他答案嘗試了這些,但都沒有奏效:
var timeInDay: TimeOfDay = TimeOfDay[selectedOption];
以上給出了TS7053錯誤。
var timeInDay: TimeOfDay = <TimeOfDay>selectedOption;
以上是給出TS17008和TS2604錯誤。
var timeInDay: TimeOfDay = (<any>TimeOfDay)[selectedOption];
以上是給出TS2339和TS17008錯誤。
我在這個網站上瀏覽了很多答案,但沒有找到解決方案。
uj5u.com熱心網友回復:
以下是一些使用string字串列舉型別的方法:
TS游樂場
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/436134.html
上一篇:如何將物件陣列轉換為一個物件
