以下代码在 TypeScript 2.0 中运行良好:
function enumDemo() {
enum temperature{
cold,
hot
};
let temp = temperature.cold;
switch (temp) {
case temperature.cold:
console.log("Brrr...");
break;
case temperature.hot:
console.log("yikes!");
break;
}
}
enumDemo();
但是,它在 tsc 2.3.4 编译器版本中产生以下错误:
Type 'temperature.hot' is not comparable to type 'temperature.
TypeScript 2.0 和 2.3 之间发生了哪些变化?
最佳答案
编辑
这是每个版本的重大更改列表,链接到我认为您正在寻找的更改。总结一下:
对于 const 声明和只读属性,默认情况下不会推断字符串、数字、 bool 值和枚举文字类型。这意味着您的变量/属性的类型比以前更窄。这可以通过使用 === 和 !== 等比较运算符来体现。
const DEBUG = true; // Now has type `true`, previously had type `boolean`
if (DEBUG === false) { /// Error: operator '===' can not be applied to 'true' and 'false'
...
}
所以不要忘记声明你的类型,毕竟它是 typescript 。如果将 temp 更改为 temp: number,如下所示:
function enumDemo() {
enum temperature{
cold,
hot
};
let temp: number = temperature.cold;
switch (temp) {
case temperature.cold:
console.log("Brrr...");
break;
case temperature.hot:
console.log("yikes!");
break;
}
}
应该可以正常工作。发生的情况是编译器尝试分配枚举类型,而不是枚举代表的数字。
替代方法是创建一个带有静态成员而不是枚举的类
export class temperature {
public static cold: number = 0;
public static hot: number = 1;
}
关于Typescript 枚举赋值编译器重大更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44480130/