【问题标题】:TypeScript compiler error for Enum in Switch statementSwitch 语句中 Enum 的 TypeScript 编译器错误
【发布时间】:2018-02-22 04:00:28
【问题描述】:

为什么 TypeScript 编译器(版本 2.7.2)显示错误消息“error TS2678: Type 'Enum1.b' is not compatible to type 'Enum1.a'”顺序?

const enum Enum1 {a, b};

let e1: Enum1 = Enum1.a;

for (let i = 0; i < 10; i++) {
   const newE1 = (i % 2 == 0) ? Enum1.a : Enum1.b;
   setE1(newE1);
   switch (e1) {
      case Enum1.a:
         console.log("a");
         break;
      case Enum1.b:
         console.log("b");
         break;
   }
}

function setE1 (newE1: Enum1) {
   e1 = newE1;
}

当我将switch(e1) 替换为switch(+e1) 时,不会出现错误。

【问题讨论】:

    标签: typescript enums switch-statement


    【解决方案1】:

    简化:

    const enum Enum1 {a, b};
    let e1: Enum1 = Enum1.a;
    
    setE1(Enum1.b);
    // Error === cannot be applied to Enum1.a and Enum1.b
    if (e1 === Enum1.b) console.log('yup'); // But it is
    
    function setE1(newE1: Enum1) {
       e1 = newE1;
    }
    

    似乎是推理引擎中的一个错误。你应该在这里报告:https://github.com/Microsoft/TypeScript/issues

    【讨论】:

    • 谢谢,我已经举报here
    • 我找到了另一种解决方法:let e1: number = Enum1.a; 而不是 let e1: Enum1 = Enum1.a;
    • 另一种解决方法:let e1: Enum1 = &lt;Enum1&gt;Enum1.a; 或 let e1 = &lt;Enum1&gt;Enum1.a;
    【解决方案2】:

    如果您在带有类型参数的函数中使用 switch 表达式,则可以按预期工作。

    例子:

    const enum Enum1 {a, b};
    
    function testSwitch(e1: Enum1) {
        switch (e1) {
            case Enum1.a:
                console.log("a");
                break;
            case Enum1.b:
                console.log("b");
                break;
        }
    }
    
    testSwitch(Enum1.a)
    

    将编译?并输出a?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-06
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 2020-01-14
      相关资源
      最近更新 更多