如何增加打字稿中的枚举? [英] How to increment an Enum in Typescript?

查看:46
本文介绍了如何增加打字稿中的枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,MyEnum是这种TS枚举(数字,连续):

Let's say, MyEnum is a TS Enum of this kind (numeric, continuous):

export enum MyEnum { 
    optionOne, 
    optionTwo,
    // more opions ...
}

,我想将其递增1,并将结果用作下一个方法调用的参数.这使编译器感到高兴:

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 ...
}

是否有一种更简单(且类型安全)的方法来获取 nextEnumValue ?

Is there an easier (and type-safer) way to obtain nextEnumValue?

推荐答案

我建议将此行为保持在枚举中,以便更明显地需要对其进行更新(或至少对其进行复审)如果对值进行了任何更改.例如,使用 Fenton在此处的答案:

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:

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);

这不需要任何类型断言(因为 Color 实际上是 0 | 1 | 2 ,是 number 的子集),并且如果您将非数字值添加到枚举,将开始引发编译器错误.但是请注意,编译器将 not 更改为非连续但仍为数值的问题,例如更改为位标记样式的值:

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. However note that the compiler will not have a problem with a change to non-consecutive but still numeric values, e.g. changing to bit flag-style values:

enum Color {
  RED = 1,
  GREEN = 2,
  BLUE = 4
}

您必须进行其他测试才能发现类似的问题.无论哪种方式, Color.after(Color.BLUE)都没有有意义的值.

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.

游乐场

这篇关于如何增加打字稿中的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆