Why does a switch statement on an enum throw 'not comparable to type' error?

Viewed 11548

While doing a Lynda tutorial on Typescript ( https://www.lynda.com/Visual-Studio-tutorials/TypeScript-types-part-2/543000/565613-4.html#tab ), I hit a snag. The sample code illustrates how switch statements work in TypeScript but the code that seems to work fine for the instructor throws a Type 'x' is not comparable to type 'y' error. Here's the code:

enum temperature{
    cold,
    hot
}

let temp = temperature.cold;

switch (temp) {
    case temperature.cold:
        console.log("Brrr....");
        break;
    case temperature.hot:
        console.log("Yikes...")
        break;
}

I get an error and squiggles under case temperature.hot: saying:

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

What gives?

4 Answers

Another possible reason could be if you check if the enum variable is not null but this also triggers if enumVal is 0. This only holds true if the enum has the default numeric values (so first item gets the value of 0)

if (!!enumVal) {
    switch (enumVal) {
         case EnumClass.First // the if clause automatically excludes the first item

In my case the problem was as @Kris mentioned.
I had to add

if (icon !== null) {
    switch (icon) {

or change the first value of the enum to be 1 instead of 0

export enum ICON_TYPE {
    ICON_A = 1,
    ICON_B = 2
}

This answer is very good however it does not give an example of casting. Here I use casting to disregard the compiler's knowledge of the constant debug_level.

type DebugLevel = 'log' | 'warn' | 'error';

const debug_lvl: DebugLevel = 'warn';

switch((debug_lvl as DebugLevel)){
  case 'error':
    console.error(...args);
    break;

  case 'warn':
    console.warn(...args);
    break;

  case 'log':
    console.log(...args);
    break;
}
Related