1

Why does the TypeScript compilier (version 2.7.2) show the error message "error TS2678: Type 'Enum1.b' is not comparable to type 'Enum1.a'" for the following code sequence?

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;
}

When I replace switch(e1) with switch(+e1), the error does not occur.

2 Answers 2

1

Simplification :

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;
}

Seems like a bug in the inference engine. You should report it here : https://github.com/Microsoft/TypeScript/issues

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, I have reported it here
I have found another workaround: let e1: number = Enum1.a; instead of let e1: Enum1 = Enum1.a;
Another workaround: let e1: Enum1 = <Enum1>Enum1.a; or let e1 = <Enum1>Enum1.a;
0

If you use the switch expression in a function with typed parameter, this works as expected.

Example:

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)

will compile 🥳 and output a 👍

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.