我正在研究TypeScript中的枚举,并为测试目的编写了以下代码:
enum IntMood {
good = 1,
neutral = 2,
bad = 3,
}
enum StringMood {
good = "1",
neutral = "2",
bad = "3",
}
const m1: IntMood = 1;
const m2: IntMood = 2349875; // no error?
const m3: StringMood = "1"; // Error: Type '"1"' is not assignable to type 'StringMood'
这是怎么回事?为什么TypeScript具有这种方式?
请注意,我对这里的TypeScript开发人员和编译器内部结构的推理感兴趣,而不对如何正确将整数/字符串转换为枚举类型转换为枚举类型感兴趣。毕竟,the latter question already been answered extensively(尽管可能会争辩说,目前所有的解决方案都很难看)。