使用typescript在枚举上迭代,然后分配给枚举



我正在尝试迭代枚举中的所有值,并将每个值分配给一个新的枚举。这就是我想到的。。。。

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];也编译无错误。我在这里做错了什么,因为西装和颜色的两个例子看起来和我一模一样。

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

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

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

谢谢,

对于字符串枚举,如果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就可以了。

您可以使用此破解:

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

相关内容

最新更新