Typescript枚举分配编译器破坏变化

时间:2017-06-11 03:32:42

标签: typescript

以下代码适用于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之间有什么变化?

1 个答案:

答案 0 :(得分:2)

<强> 修改

https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#literal-types-are-inferred-by-default-for-const-variables-and-readonly-properties

这是每个版本的重大更改列表,与我认为您正在寻找的更改相关联。总结:

对于const声明和readonly属性,默认情况下不会推断字符串,数字,布尔和枚举文字类型。这意味着您的变量/属性的类型比以前更窄。这可能表现在使用比较运算符,例如===和!==。

const DEBUG = true; // Now has type `true`, previously had type `boolean`

if (DEBUG === false) { /// Error: operator '===' can not be applied to 'true' and 'false'
    ...
}

所以不要忘记声明你的类型,毕竟它是打字稿。如果你将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;
}