【问题标题】:Iterate over an enum with typescript and assign to an enum使用打字稿迭代枚举并分配给枚举
【发布时间】:2018-07-11 08:21:41
【问题描述】:

我正在尝试遍历枚举中的所有值,并将每个值分配给一个新的枚举。这就是我想出的......

enum Color {
    Red, Green
}

enum Suit { 
    Diamonds, 
    Hearts, 
    Clubs, 
    Spades 
}

class Deck 
{
    cards: Card[];

    public fillDeck() {
        for (let suit in Suit) {
            var mySuit: Suit = Suit[suit];
            var myValue = 'Green';
            var color : Color = Color[myValue];
        }
    }
}

var mySuit: Suit = Suit[suit];部分没有编译,返回错误Type 'string' is not assignable to type 'Suit'

如果我在 for 循环中将鼠标悬停在 suit 上,它会显示 let suit: stringvar color : Color = Color[myValue]; 也编译没有错误。我在这里做错了什么,因为 Suit 和 Color 的两个示例看起来都与我相同。

我使用的是 TypeScript 版本 2.9.2,这是我的 tsconfig.json 的内容

{
    "compilerOptions": {
        "target": "es6",
        "module": "commonjs",
        "sourceMap": true
    }
}

有没有更好的方法来迭代枚举中的所有值,同时保持每次迭代的枚举类型?

谢谢,

【问题讨论】:

    标签: typescript enums


    【解决方案1】:

    对于字符串枚举,如果strict 标志打开,我们将得到type string can't be used to index type 'typeof Suit'。 所以我们必须这样做:

    for (const suit in Suit) {
        const mySuit: Suit = Suit[suit as keyof typeof Suit];
    }
    

    如果你只需要它的string值,那么直接使用suit就可以了。

    【讨论】:

      【解决方案2】:

      您可以使用此 hack:

      const mySuit: Suit = Suit[suit] as any as Suit;
      

      或将Suit枚举更改为字符串枚举并像这样使用它:

      enum Suit { 
          Diamonds = "Diamonds", 
          Hearts = "Hearts", 
          Clubs = "Clubs", 
          Spades = "Spades",
      }
      
      for (let suit in Suit) {
          const mySuit: Suit = Suit[suit] as Suit;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-04-30
        • 2020-01-29
        • 1970-01-01
        • 2022-12-05
        • 2019-03-04
        • 2017-05-09
        • 2011-02-07
        相关资源
        最近更新 更多