2

The following code used to work fine with 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();

However, it is producing the below error in tsc 2.3.4 compiler versions:

Type 'temperature.hot' is not comparable to type 'temperature.

What has been changed between TypeScript 2.0 and 2.3?

1 Answer 1

2

Edit

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

This is the list of breaking changes per version, linked to what I think is the change you're looking for. In summary:

String, numeric, boolean and enum literal types are not inferred by default for const declarations and readonly properties. This means your variables/properties an have more narrowed type than before. This could manifest in using comparison operators such as === and !==.

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

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

So don't forget to declare you types, it is typescript after all. If you change temp to temp: number like so:

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

It should work fine. What's happening is the compiler is trying to assign the enum type, rather than the number the enum represents.

And alternative method would be to make a class with static members instead of an enum

export class temperature {
    public static cold: number = 0;
    public static hot: number = 1;
}
Sign up to request clarification or add additional context in comments.

3 Comments

This code used to work without error in TypeScript 2.0. The question is "What has been changed between TypeScript 2.0 and 2.3?"
Shouldn't it be let temp: temperature = temperature.cold;?
@torazaburo that creates the same compilation error. You would think it would be fine, and I think it would look and feel nicer than type of number, but it doesn't seem to work that way. I just pulled it up in my VS Code, and it's showing the temp type as 'temperature.cold', even though the type definition was for the enum, and not the value (let temp: temperature = temperature.cold)

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.