我有一个看起来像这样的打字稿枚举:
enum State {
NotRequired,
Working,
PendingReview,
Reviewed,
Done
}
这就产生了这个:
var State;
(function (State) {
State[State["NotRequired"] = 0] = "NotRequired";
State[State["Working"] = 1] = "Working";
State[State["PendingReview"] = 2] = "PendingReview";
State[State["Reviewed"] = 3] = "Reviewed";
State[State["Done"] = 4] = "Done";
})(State || (State = {}));
我希望将值设置为带有空格的字符串。
因此State[State["PendingReview"] = 2] = "PendingReview";
将成为State[State["PendingReview"] = 2] = "Pending Review";
我已经设法通过如此定义我的枚举来实现与此类似的东西:
enum State {
"Not Required",
Working,
"Pending Review",
Reviewed,
Done
}
然而,这有一个缺点,即在代码中使用任何枚举值时,我现在必须使用我的密钥。
现在必须像State.PendingReview
State["Pending Review"]
我可以通过某种方式为我的键定义另一个显示字符串,从而获得两全其美的效果吗?
因此,当我说State[State.PendingReview]
时,它会给我"Pending Review"
答案 0 :(得分:1)
由于枚举不支持字符串值, 使用像这样的静态字段的类会更好。
您有编辑检查,就像使用枚举一样,您也可以在代码中以相同的方式调用它。
module rizze.tests {
enum State{
NotRequiered,
Working,
Pending,
Reviewed,
Done
}
class StateConvert {
static NotRequiered="Not Required";
static Working="I'm Working";
static Pending = "Pending Review";
static Reviewed="Reviewed Done";
static Done="Done All";
static convert(state:State):String{
if( state == null) return null;
switch(state){
case State.NotRequiered:{return StateConvert.NotRequiered;}
case State.Working:{return StateConvert.Working;}
case State.Pending:{return StateConvert.Pending;}
case State.Reviewed:{return StateConvert.Reviewed;}
case State.Done:{return StateConvert.Done;}
}
console.log("Error state undefined + " +state );
return null;
}
}
export class StateTest {
constructor(){
let state:State = State.Reviewed;
console.log("state:"+state + " / " + StateConvert.convert(state));
}
}
//TEST
let s:StateTest= new StateTest();
}
答案 1 :(得分:1)
由于您没有为枚举指定显式值,您也可以为此使用字符串枚举(从 TypeScript 2.4 开始可用):
enum State {
NotRequired = "Not Required",
Working = "Working",
PendingReview = "Pending Review",
Reviewed = "Reviewed",
Done = "Done"
}
显示值然后简单地变成例如State.NotRequired
。
答案 2 :(得分:0)
通过某种方式定义另一种选择,我能否拥有两全其美的优势 将字符串显示到我的密钥?
没有。 TypeScript不支持此功能。如果您认为这样做有价值,可以尝试制作feature request。