[英]How to increment an Enum in Typescript?
Let's say, MyEnum is a TS Enum of this kind (numeric, continuous):假设 MyEnum 是这种类型的 TS 枚举(数字,连续):
export enum MyEnum {
optionOne,
optionTwo,
// more opions ...
}
and I want to increment it by one and use the result as a parameter for the next method call.我想将它加一并将结果用作下一个方法调用的参数。 This makes the compiler happy:这让编译器很高兴:
private DoSomething(currentValue: MyEnum): void {
let nextEnumValue = <MyEnum>(<number><unknown>currentValue + 1);
this.DoMore(nextEnumValue);
}
private DoMore(currentValue: MyEnum): void {
// Something ...
}
Is there an easier (and type-safer) way to obtain nextEnumValue
?有没有更简单(和类型更安全)的方法来获取nextEnumValue
?
I would suggest keeping this behaviour with the enum, so that it's more obvious it needs to be updated (or at least reviewed) if any change is made to the values.我建议将这种行为与枚举一起保留,以便更明显的是,如果对值进行了任何更改,则需要更新(或至少审查)。 For example, using the namespace idea from Fenton's answer here :例如,使用Fenton's answer here 中的命名空间想法:
enum Color {
RED,
GREEN,
BLUE
}
namespace Color {
export function after(value: Color): Color {
return value + 1;
}
}
// In use
const color: Color = Color.after(Color.RED);
This doesn't require any type assertions (because Color
is effectively 0 | 1 | 2
, a subset of number
), and will start throwing a compiler error if you add non-numeric values to the enumeration.这不需要任何类型断言(因为Color
实际上是0 | 1 | 2
,一个number
的子集),并且如果您向枚举添加非数字值,将开始引发编译器错误。 However note that the compiler will not have a problem with a change to non-consecutive but still numeric values, eg changing to bit flag-style values:但是请注意,编译器在更改非连续但仍然是数字值时不会有问题,例如更改为位标志样式值:
enum Color {
RED = 1,
GREEN = 2,
BLUE = 4
}
You'd have to have other tests to catch issues like that.您必须进行其他测试才能发现此类问题。 It also doesn't deal with the fact that, either way, Color.after(Color.BLUE)
doesn't have a meaningful value.它也没有处理这样一个事实,无论哪种方式, Color.after(Color.BLUE)
都没有有意义的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.