【发布时间】: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: string。 var color : Color = Color[myValue]; 也编译没有错误。我在这里做错了什么,因为 Suit 和 Color 的两个示例看起来都与我相同。
我使用的是 TypeScript 版本 2.9.2,这是我的 tsconfig.json 的内容
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"sourceMap": true
}
}
有没有更好的方法来迭代枚举中的所有值,同时保持每次迭代的枚举类型?
谢谢,
【问题讨论】:
标签: typescript enums